c#定时任务写到数据库
时间: 2023-07-04 14:19:28 浏览: 106
您可以使用 System.Timers 命名空间中的 Timer 类在 C# 中创建定时任务,并将任务信息写入数据库。
下面是一个示例代码,它将每分钟执行一次任务并将任务信息写入 MySQL 数据库中:
```
using System;
using System.Timers;
using MySql.Data.MySqlClient;
namespace TimerExample
{
class Program
{
static void Main(string[] args)
{
// 创建定时器
Timer timer = new Timer(60000); // 每分钟执行一次任务
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
// 保持程序运行
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// 连接数据库
string connectionString = "server=localhost;database=mydb;uid=myuser;pwd=mypass;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
// 执行任务并将任务信息写入数据库
MySqlCommand command = new MySqlCommand("INSERT INTO tasks (name, description) VALUES (@name, @description)", connection);
command.Parameters.AddWithValue("@name", "TaskName");
command.Parameters.AddWithValue("@description", "TaskDescription");
command.ExecuteNonQuery();
}
}
}
}
```
在这个示例代码中,我们使用了 Timer.Elapsed 事件来绑定一个事件处理程序,在每次定时器触发时执行 OnTimedEvent 方法。在 OnTimedEvent 方法中,我们连接到 MySQL 数据库,并将任务信息插入到 tasks 表中。
当然,您可以根据自己的需要修改代码来连接到不同的数据库或执行不同的任务。