在C#中,使用Task Scheduler庫可以方便地創(chuàng)建和管理任務(wù)。但是,默認(rèn)情況下,任務(wù)調(diào)度器并不支持任務(wù)的持久化。為了實現(xiàn)任務(wù)的持久化,你需要將任務(wù)數(shù)據(jù)存儲在持久性存儲中,例如數(shù)據(jù)庫或文件系統(tǒng)。
以下是一個簡單的示例,展示了如何使用SQLite數(shù)據(jù)庫實現(xiàn)任務(wù)持久化:
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; }
}
現(xiàn)在,你可以使用TaskScheduler
類創(chuàng)建、讀取和更新任務(wù),這些任務(wù)的數(shù)據(jù)將被持久化到SQLite數(shù)據(jù)庫中。你可以根據(jù)實際需求擴(kuò)展此示例,例如添加刪除任務(wù)的功能。