在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數據庫中。你可以根據實際需求擴展此示例,例如添加刪除任務的功能。