Quartz.NET是一個開源的作業調度框架,非常適合在日常工作中做一些定時任務。
在Windows系統中,我們可以直接新建一個Windows Service項目,進行相應的編碼生成一個exe程序並部署為 Windows服務,啟動服務,即可定時執行任務。
在Linux系統中,由於Windows 服務只能運行在Windows系統上,所以想達到上面的目標,創建一個控制台應用程序是更好的選擇。
開發環境
Windows 10 ,visual studio 2019,版本16.6.1,.net core 3.1
運行環境
CentOS Linux release 7.5.1804 (Core)

1 static void Main(string[] args) 2 { 3 IScheduler scheduler; 4 ISchedulerFactory factory = new StdSchedulerFactory(); 5 scheduler = factory.GetScheduler().Result; 6 IJobDetail testJobDetail = JobBuilder.Create<TestJob>().WithIdentity("testJob").Build(); 7 ITrigger testJobTrigger = TriggerBuilder.Create().WithCronSchedule("0/2 * * * * ? *").Build(); 8 scheduler.ScheduleJob(testJobDetail, testJobTrigger); 9 scheduler.Start(); 10 while (true) 11 { 12 Thread.Sleep(50); 13 } 14 }

1 public class TestJob:IJob 2 { 3 public Task Execute(IJobExecutionContext context) 4 { 5 return Task.Run(() => 6 { 7 var content = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"; 8 9 string path = "/test.log"; 10 using (StreamWriter sw=new StreamWriter(path,true)) 11 { 12 sw.WriteLine(content); 13 } 14 }); 15 } 16 }
發布配置
之后上將生成的文件上傳到Linux服務器
執行以下代碼
vi /lib/systemd/system/your-service-name.service #insert the following #your service description [Unit] Description=Test Service #your console app path [Service] ExecStart=/wwwroot/test/demo.Jobs [Install] WantedBy=default.target
保存之后執行以下代碼
systemctl daemon-reload systemctl start your-service-name.service systemctl status your-service-name.service
上圖表示服務正常運行
運行命令
cat /test.log
即可看到示例中正常記錄的時間