在C#中,使用Task Scheduler库可以方便地创建和管理任务。但是,默认情况下,任务调度器并不支持任务的持久化。为了实现任务的持久化,你需要将任务数据存储在持久性存储中,例如数据库或文件系统。
以下是一个简单的示例,展示了如何使用SQLite数据库实现任务持久化:
System.Data.SQLite
包。Install-Package System.Data.SQLite
tasks
的表,包含Id
、Name
、Description
和LastExecutionTime
字段。CREATE TABLE tasks (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Description TEXT,
LastExecutionTime DATETIME
);
using System;
using System.Data.SQLite;
class TaskScheduler
{
private static string dbPath = "path/to/your/database.db";
public static void CreateTask(string name, string description)
{
using (SQLiteConnection connection = new SQLiteConnection($"Data Source={dbPath};"))
{
connection.Open();
string sql = "INSERT INTO tasks (Name, Description) VALUES (?, ?)";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@description", description);
command.ExecuteNonQuery();
}
}
}
public static TaskInfo GetTaskById(int id)
{
using (SQLiteConnection connection = new SQLiteConnection($"Data Source={dbPath};"))
{
connection.Open();
string sql = "SELECT * FROM tasks WHERE Id = @id";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.Parameters.AddWithValue("@id", id);
using (SQLiteDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return new TaskInfo
{
Id = reader["Id"].ToInt32(),
Name = reader["Name"].ToString(),
Description = reader["Description"].ToString(),
LastExecutionTime = reader["LastExecutionTime"].ToDateTime()
};
}
}
}
}
return null;
}
public static void UpdateTask(TaskInfo task)
{
using (SQLiteConnection connection = new SQLiteConnection($"Data Source={dbPath};"))
{
connection.Open();
string sql = "UPDATE tasks SET Name = @name, Description = @description, LastExecutionTime = @lastExecutionTime WHERE Id = @id";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.Parameters.AddWithValue("@id", task.Id);
command.Parameters.AddWithValue("@name", task.Name);
command.Parameters.AddWithValue("@description", task.Description);
command.Parameters.AddWithValue("@lastExecutionTime", task.LastExecutionTime);
command.ExecuteNonQuery();
}
}
}
}
class TaskInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime LastExecutionTime { get; set; }
}
现在,你可以使用TaskScheduler
类创建、读取和更新任务,这些任务的数据将被持久化到SQLite数据库中。你可以根据实际需求扩展此示例,例如添加删除任务的功能。