.Net Core 3.1 +Topshelf+Quartz创建Windows定时任务
准备工作
- 创建.net core 控制台应用程序,这里不做过多介绍
- 添加TopShelf包:TopShelf;
- 添加Quartz包:Quartz、Quartz.Plugins;
- 添加依赖注入包:Microsoft.Extensions.DependencyInjection;
- 添加读取配置文件包:Microsoft.Extensions.Configuration.Json;
- 添加访问数据库包:Microsoft.EntityFrameworkCore;
配置Quartz
- 创建appsettings.json文件,右键文件属性,并更改属性为始终复制 内容
123456789101112131415161718
{"quartz": {"scheduler": {"instanceName":"Job"},"threadPool": {"type":"Quartz.Simpl.SimpleThreadPool, Quartz","threadPriority":"Normal","threadCount": 10},"plugin": {"jobInitializer": {"type":"Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins","fileNames":"quartz_jobs.xml"}}}} - 创建QuartzOption 类
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
publicclassQuartzOption{publicQuartzOption(IConfiguration config){if(config ==null){thrownewArgumentNullException(nameof(config));}varsection = config.GetSection("quartz");section.Bind(this);}publicScheduler Scheduler {get;set; }publicThreadPool ThreadPool {get;set; }publicPlugin Plugin {get;set; }publicNameValueCollection ToProperties(){varproperties =newNameValueCollection{["quartz.scheduler.instanceName"] = Scheduler?.InstanceName,["quartz.threadPool.type"] = ThreadPool?.Type,["quartz.threadPool.threadPriority"] = ThreadPool?.ThreadPriority,["quartz.threadPool.threadCount"] = ThreadPool?.ThreadCount.ToString(),["quartz.plugin.jobInitializer.type"] = Plugin?.JobInitializer?.Type,["quartz.plugin.jobInitializer.fileNames"] = Plugin?.JobInitializer?.FileNames};returnproperties;}}publicclassScheduler{publicstringInstanceName {get;set; }}publicclassThreadPool{publicstringType {get;set; }publicstringThreadPriority {get;set; }publicintThreadCount {get;set; }}publicclassPlugin{publicJobInitializer JobInitializer {get;set; }}publicclassJobInitializer{publicstringType {get;set; }publicstringFileNames {get;set; }} -
添加一个Job
123456789101112131415publicclassTestJob : IJob{privatereadonlyIService _service;publicSyncJob(IService service){_service = service;}publicasync Task Execute(IJobExecutionContext context){Log.Information("同步开始...");_service.DoSomeThing();}} -
实现IJobFactory
12345678910111213141516171819publicclassJobFactory : IJobFactory{protectedreadonlyIServiceProvider Container;publicJobFactory(IServiceProvider container){Container = container;}publicIJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler){returnContainer.GetService(bundle.JobDetail.JobType)asIJob;}publicvoidReturnJob(IJob job){(jobasIDisposable)?.Dispose();}} -
创建Quartz调度的配置文件 quartz_jobs.xml
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455<?xml version="1.0"encoding="UTF-8"?><!-- This file contains job definitionsinschema version 2.0 format --><job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"version="2.0"><processing-directives><overwrite-existing-data>true</overwrite-existing-data></processing-directives><schedule><!--TestJob测试 任务配置--><job><name>TestJob</name><group>ServerGroup</group><description>上传视频</description><job-type>Server.TestJob, Server</job-type><durable>true</durable><recover>false</recover></job><trigger><cron><name>TestJobTrigger</name><group>ServerGroup</group><job-name>TestJob</job-name><job-group>ServerGroup</job-group><cron-expression>0/60 * * * * ?</cron-expression></cron></trigger><!--TestJob2测试 任务配置--><!--<job><name>TestJob2</name><group>Test</group><description>TestJob2测试</description><job-type>CoreSolution.Job.jobs.TestJob2,CoreSolution.Job</job-type><durable>true</durable><recover>false</recover></job><trigger><cron><name>TestJob2Trigger</name><group>Test</group><job-name>TestJob2</job-name><job-group>Test</job-group><cron-expression>0/30 * * * * ?</cron-expression>--><!--30s执行一次--><!--</cron></trigger>--></schedule></job-scheduling-data> -
添加一个类,此类用户服务启动调用
-
1234567891011121314151617181920212223242526272829303132333435
publicsealedclassServiceRunner : ServiceControl, ServiceSuspend{//调度器privatereadonlyIScheduler scheduler;publicServiceRunner(){scheduler = StdSchedulerFactory.GetDefaultScheduler().GetAwaiter().GetResult();}//开始publicboolStart(HostControl hostControl){scheduler.Start();returntrue;}//停止publicboolStop(HostControl hostControl){scheduler.Shutdown(false);returntrue;}//恢复所有publicboolContinue(HostControl hostControl){scheduler.ResumeAll();returntrue;}//暂停所有publicboolPause(HostControl hostControl){scheduler.PauseAll();returntrue;}} -
配置TopShelf
123456789101112131415161718192021222324252627classProgram{staticvoidMain(string[] args){varrc = HostFactory.Run(x =>{x.Service<ServiceRunner>(s => {s.ConstructUsing(name =>newServiceRunner());s.WhenStarted((tc, hc) => tc.Start(hc));s.WhenStopped((tc, hc) => tc.Stop(hc));s.WhenContinued((tc, hc) => tc.Continue(hc));s.WhenPaused((tc, hc) => tc.Pause(hc));});x.RunAsLocalService();x.StartAutomaticallyDelayed();x.RunAsLocalSystem();x.SetDescription("测试后台服务");x.SetDisplayName("TestServer");x.SetServiceName("TestServer");x.EnablePauseAndContinue();});varexitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());Environment.ExitCode = exitCode;}}

浙公网安备 33010602011771号