2 回答
TA貢獻1794條經驗 獲得超8個贊
您可以使用任務計劃程序Windows
任務計劃程序可用于執行任務,例如啟動應用程序、發送電子郵件或顯示消息框。可以安排任務執行:
在特定時間。
在每日計劃的特定時間。
你可以試試這個為每一天動態創建一個任務,
using System;
using Microsoft.Win32.TaskScheduler;
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch your application whenever the trigger fires
td.Actions.Add(new ExecAction("my_application.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
你編寫你my_application.exe的連接 API 和拉到數據庫。接下來,配置創建的任務以調用您的應用程序。
Quartz也是一個選項,具有更豐富的 API 來創建任務并將其保存到數據庫。但我認為Windows Scheduled任務可能會給你所有你需要的。
TA貢獻1829條經驗 獲得超7個贊
你應該看看 Quartz .NET:
https://www.quartz-scheduler.net/
如果我理解正確,它將從 SQL 數據庫中獲取它需要運行的時間,因此您的 Windows 服務可能應該每隔一段時間檢查一次,是否已更新計劃并在應用程序中重新計劃(如果相關)。
另一個非常好的項目是 Hangfire:
https://www.hangfire.io/
任何一個都可能允許您做您需要的事情。
這是您可以執行的操作的示例(在 Hangfire 中):
// Get database times. For simplicity I'll assume that you
// just get a list of dates. Assume they're stored in in UTC
List<DateTime> times = this.database.GetSchedule();
// Loop the times and schedule jobs
foreach(var time in times)
{
var timeUntilJob = time - DateTime.UtcNow;
var jobId = BackgroundJob.Enqueue(() => YourMethodToDoWork(), timeUntilJob);
// You will need to somehow store the job ids, in case you want to
// cancel an execution scheduled for a later time (e.g. if you
// need to update it if the database-stored schedule changes).
// You could then invoke BackgroundJob.Delete(jobId)
}
Hangfire 可以將預定的調用存儲在 SQL Server 數據庫(或 Redis 或 MongoDb 等)中。它創建包含要在預定時間調用的程序集、方法和參數的記錄。這意味著即使您的服務出現故障,您也不會丟失任務的執行。
您可以創建一個計時器,每 X 小時滴答一次并刪除當前計劃,并使用數據庫中的當前值進行更新。但是你想如何做到這一點當然取決于你的具體情況。
- 2 回答
- 0 關注
- 519 瀏覽
添加回答
舉報
