想要定时运行脚本,jenkins虽然可以实现,但是用的不爽,所以改成quartz试一试
灵感来自 https://tech.youzan.com/youzan-online-active-testing/
quartz官方教程 http://www.quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/tutorial-lesson-06.html
概念
想要执行的job
多长时间触发一次
我的疑问?
-
怎么实现job和trigger的可配置呢?
例如我想执行一个类,但是呢?如果这个类定义了,是不是就固定了?除非可以额外传参数,google下真的可以传参数。【How to pass instance variables into Quartz job?】 -
怎么实现任务的终止呢?
不是调度器的终止,是任务的终止。
Try make your job implements org.quartz.InterruptableJob, and then you may call org.quartz.Scheduler.interrupt(JobKey).
// quartz.properties
org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
package com.qlkj;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
@Override
public void execute(JobExecutionContext var1) throws JobExecutionException{
System.out.println("hello world");
System.out.println(System.currentTimeMillis());
}
}
package com.qlkj;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.*;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
public class QuartzTest {
public static void main(String[] args) {
try {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// and start it off
scheduler.start();
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class)
.withIdentity("job1", "group1")
.build();
// Trigger the job to run now, and then repeat every 40 seconds
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(5)
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);
// scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
CronTrigger
CronTrigger使用cron-expressions进行任务触发,cron表达式从左到右依次代表着
Seconds
Minutes
Hours
Day-of-Month
Month
Day-of-Week
Year (optional field)
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(cronSchedule("0 0/2 8-17 * * ?"))
.forJob("myJob", "group1")
.build();