使用quartz-scheduler实现定时任务
2018-03-29 本文已影响17人
云师兄
首先pom.xml文件中添加依赖:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
下面是一个实现定时任务的demo:
private static final int TIME = 2;
public void startAutoJob() throws Exception{
/*
*在 Quartz 中, scheduler 由 scheduler 工厂创建:DirectSchedulerFactory 或者 StdSchedulerFactory。第二种工厂 StdSchedulerFactory 使用较多,
*因为 DirectSchedulerFactory 使用起来不够方便,需要作许多详细的手工编码设置。
*/
// 获取Scheduler实例
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
System.out.println("scheduler.start");
//具体任务.
JobDetail jobDetail = JobBuilder.newJob(WeatherDataSyncJob.class).withIdentity("job1","group1").build();
//触发时间点. (每5秒执行1次.)
SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(TIME).repeatForever();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1","group1").startNow().withSchedule(simpleScheduleBuilder).build();
// 交由Scheduler安排触发
scheduler.scheduleJob(jobDetail,trigger);
//睡眠20秒.
//TimeUnit.SECONDS.sleep(20);
//scheduler.shutdown();//关闭定时任务调度器.
//System.out.println("scheduler.shutdown");
}
具体执行定时任务的类代码如下:
public class WeatherDataSyncJob extends QuartzJobBean {
private final static Logger logger = LoggerFactory.getLogger(WeatherDataSyncJob.class);
//@Autowired
//private WeatherDataService weatherDataService;
/* (non-Javadoc)
* @see org.springframework.scheduling.quartz.QuartzJobBean#executeInternal(org.quartz.JobExecutionContext)
*/
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
logger.info("Weather Data Sync Job. Start!");
}
}
执行startAutoJob方法后每隔2秒钟就会打印执行类中的日志。