准备工作
- 创建.net Framwork 控制台应用程序
- 添加TopShelf包:TopShelf;
- 添加Quartz包:Quartz、Quartz.Plugins;
配置quartz.config
# You can configure your scheduler in either<quartz> configuration section # or in quartz properties file # Configuration section has precedence quartz.scheduler.instanceName = ServerScheduler # configure thread pool info quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz quartz.threadPool.threadCount = 10 quartz.threadPool.threadPriority = Normal # job initialization plugin handles our xml reading, without it defaults are used quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins quartz.plugin.xml.fileNames = ~/quartz_jobs.xml
配置quartz_jobs.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- This file contains job definitions in schema 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> </schedule> </job-scheduling-data>
添加一个类,此类用户服务启动调用
public sealed class ServiceRunner : ServiceControl, ServiceSuspend { //调度器 private readonly IScheduler scheduler; public ServiceRunner() { scheduler = StdSchedulerFactory.GetDefaultScheduler().GetAwaiter().GetResult(); } //开始 public bool Start(HostControl hostControl) { scheduler.Start(); return true; } //停止 public bool Stop(HostControl hostControl) { scheduler.Shutdown(false); return true; } //恢复所有 public bool Continue(HostControl hostControl) { scheduler.ResumeAll(); return true; } //暂停所有 public bool Pause(HostControl hostControl) { scheduler.PauseAll(); return true; } }
配置TopShelf
class Program { static void Main(string[] args) { var rc = HostFactory.Run(x => { x.Service<ServiceRunner>(s => { s.ConstructUsing(name => new ServiceRunner()); 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(); }); var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); Environment.ExitCode = exitCode; } }