Quartz 简单使用
Posted VipSoft
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Quartz 简单使用相关的知识,希望对你有一定的参考价值。
Scheduler 每次执行,都会根据JobDetail创建一个新的Job实例,这样就可以规避并发访问的问题(jobDetail的实例也是新的)
Quzrtz 定时任务默认都是并发执行,不会等待上一次任务执行完毕,只要间隔时间到就会执行,如果定时任务执行太长,会长时间占用资源,导致其它任务堵塞
@DisallowConcurrentExecution: job类上,禁止并发地执行同一个job定义 (JobDetail定义的)的多个实例。
简单示例
TestClient.Java
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class TaskClient
public static void main(String[] args)
JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
.withIdentity("job1", "group1") //设置JOB的名字和组
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "trigger1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
.repeatForever())
.build();
try
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(jobDetail,trigger);
scheduler.start();
catch (SchedulerException ex)
ex.printStackTrace();
TaskJob.Java
import cn.hutool.core.date.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TaskJob implements Job
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException
System.out.println("TaskJob => " + DateUtil.now());
usingJobData
通过 usingJobData 往定时任务中传递参数
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class TaskClient
public static void main(String[] args)
JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
.withIdentity("job1", "group1")
.usingJobData("job","jobDetail1.JobDataMap.Value")
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "trigger1")
.usingJobData("trigger","trigger.JobDataMap.Value")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
.repeatForever())
.build();
try
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(jobDetail,trigger);
scheduler.start();
catch (SchedulerException ex)
ex.printStackTrace();
TaskJob.java
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TaskJob implements Job
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
JobDataMap triggerMap = context.getTrigger().getJobDataMap();
JobDataMap mergeMap = context.getMergedJobDataMap();
System.out.println("jobDataMap => " + jobDataMap.getString("job"));
System.out.println("triggerMap => " + triggerMap.getString("trigger"));
System.out.println("mergeMap => " + mergeMap.getString("trigger"));
通过 属性赋值
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class TaskClient
public static void main(String[] args)
JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
.withIdentity("job1", "group1")
.usingJobData("job","jobDetail1.JobDataMap.Value")
.usingJobData("name","jobDetail1.name.Value") //通过 setName 自动赋值
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "trigger1")
.usingJobData("trigger","trigger.JobDataMap.Value")
.usingJobData("name","trigger.name.Value") //如果 Trigger 有值,会覆盖 JobDetail
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
.repeatForever())
.build();
try
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(jobDetail,trigger);
scheduler.start();
catch (SchedulerException ex)
ex.printStackTrace();
import org.quartz.*;
public class TaskJob implements Job
private String name;
public void setName(String name)
this.name = name;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
System.out.println("name => " + name);
非并发执行
@DisallowConcurrentExecution job类上,禁止并发地执行同一个job定义 (JobDetail定义的)的多个实例。
import cn.hutool.core.date.DateUtil;
import org.quartz.*;
@DisallowConcurrentExecution
public class TaskJob implements Job
@Override
public void execute(JobExecutionContext context)
System.out.println("Time => " + DateUtil.now());
try
Thread.sleep(3000);
catch (InterruptedException e)
e.printStackTrace();
@PersistJobDataAfterExecution
持久化JobDetail中的JobDataMap(对 trigger 中的 datamap 无效),如果一个任务不是
import cn.hutool.core.date.DateUtil;
import org.quartz.*;
//持久化JobDetail中的JobDataMap(对 trigger 中的 datamap 无效),如果一个任务不是
@PersistJobDataAfterExecution
public class TaskJob implements Job
@Override
public void execute(JobExecutionContext context)
JobDataMap triggerMap = context.getJobDetail().getJobDataMap();
triggerMap.put("count", triggerMap.getInt("count") + 1);
System.out.println("Time => " + DateUtil.now() + " count =>" + triggerMap.getInt("count"));
Client
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class TaskClient
public static void main(String[] args)
JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
.withIdentity("job1", "group1")
.usingJobData("job","jobDetail1.JobDataMap.Value")
.usingJobData("name","jobDetail1.name.Value") //通过 setName 自动赋值
.usingJobData("count",0) //通过 setName 自动赋值
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "trigger1")
.usingJobData("trigger","trigger.JobDataMap.Value")
.usingJobData("name","trigger.name.Value") //如果 Trigger 有值,会覆盖 JobDetail
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
.repeatForever())
.build();
try
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(jobDetail,trigger);
scheduler.start();
catch (SchedulerException ex)
ex.printStackTrace();
Quartz_简单使用
第一步:安装
新建一个QuartzDemo项目后,安装下面的程序包
Install-Package Quartz
Install-Package Common.Logging.Log4Net1211
Install-Package log4net
Install-Package
Topshelf
Install-Package Topshelf.Log4Net
Quartz依赖Common.Logging和Common.Logging.Log4Net1211,又因为Log4Net是比较标准的日志工具,因此我们一般都会安装log4net
,另外定时作业一般都允许在后台服务中,因此我们也安装了Topshelf。
第二步:实现IJob
TestJob.cs 实现IJob,在Execute方法里编写要处理的业务逻辑,系统就会按照Quartz的配置,定时处理。
using log4net; using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuartzDemo.QuartzJobs { public sealed class TestJob : IJob { private readonly ILog _logger = LogManager.GetLogger(typeof(TestJob)); public void Execute(IJobExecutionContext context) { _logger.InfoFormat("TestJob测试"); } } }
第三步:使用Topshelf调度任务
using Quartz; using Quartz.Impl; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Topshelf; namespace QuartzDemo { public sealed class ServiceRunner : ServiceControl, ServiceSuspend { private readonly IScheduler scheduler; public ServiceRunner() { scheduler = StdSchedulerFactory.GetDefaultScheduler(); } 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; } } }
第四步:程序入口
namespace QuartzDemo { class Program { static void Main(string[] args) { log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config")); HostFactory.Run(x => { x.UseLog4Net(); x.Service<ServiceRunner>(); x.SetDescription("QuartzDemo服务描述"); x.SetDisplayName("QuartzDemo服务显示名称"); x.SetServiceName("QuartzDemo服务名称"); x.EnablePauseAndContinue(); }); } } }
第五步:配置quartz.config、quartz_jobs.xml、log4net.config
说明:这三个文件,分别选中→右键属性→复制到输入目录设为:始终复制
# You can configure your scheduler in either <quartz> configuration section # or in quartz properties file # Configuration section has precedence quartz.scheduler.instanceName = QuartzTest # 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 quartz.plugin.xml.fileNames = ~/quartz_jobs.xml # export this server to remoting context #quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz #quartz.scheduler.exporter.port = 555 #quartz.scheduler.exporter.bindName = QuartzScheduler #quartz.scheduler.exporter.channelType = tcp #quartz.scheduler.exporter.channelName = httpQuartz
<?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>Test</group> <description>TestJob测试</description> <job-type>QuartzDemo.QuartzJobs.TestJob,QuartzDemo</job-type> <durable>true</durable> <recover>false</recover> </job> <trigger> <cron> <name>TestJobTrigger</name> <group>Test</group> <job-name>TestJob</job-name> <job-group>Test</job-group> <start-time>2015-01-22T00:00:00+08:00</start-time> <cron-expression>0/3 * * * * ?</cron-expression> </cron> </trigger> </schedule> </job-scheduling-data>
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <param name= "File" value= "D:\App_Log\servicelog\"/> <!--是否是向文件中追加日志--> <param name= "AppendToFile" value= "true"/> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日志文件名是否是固定不变的--> <param name= "StaticLogFileName" value= "false"/> <!--日志文件名格式为:2008-08-31.log--> <param name= "DatePattern" value= "yyyy-MM-dd".read.log""/> <!--日志根据日期滚动--> <param name= "RollingStyle" value= "Date"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <!-- 控制台前台显示日志 --> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="Info" /> <foreColor value="Green" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="Info" /> <param name="LevelMax" value="Fatal" /> </filter> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="ColoredConsoleAppender"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>
以上是关于Quartz 简单使用的主要内容,如果未能解决你的问题,请参考以下文章