依赖:
看一下整体结构:
首先定义Job
public class HelloJob implements Job { private static Logger _log = LoggerFactory.getLogger(HelloJob.class); public HelloJob() { } public void execute(JobExecutionContext context) throws JobExecutionException { // Say Hello to the World and display the date/time _log.info("Hello World! - " + new Date()); } }
简单触发示例
public class SimpleExample { public void run() throws Exception { Logger log = LoggerFactory.getLogger(SimpleExample.class); log.info("------- Initializing ----------------------"); // 定义调度器 SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); log.info("------- Initialization Complete -----------"); // 获取当前时间的下一分钟 Date runTime = evenMinuteDate(new Date()); log.info("------- Scheduling Job -------------------"); // 定义job // 在quartz中,有组的概念,组+job名称 唯一的 JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build(); // 定义触发器,在下一分钟启动 Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build(); // 将job注册到调度器 sched.scheduleJob(job, trigger); log.info(job.getKey() + " will run at: " + runTime); // 启动调度器 sched.start(); log.info("------- Started Scheduler -----------------"); // 等待65秒 log.info("------- Waiting 65 seconds... -------------"); try { // wait 65 seconds to show job Thread.sleep(65L * 1000L); // executing... } catch (Exception e) { // } // 关闭调度器 log.info("------- Shutting Down ---------------------"); sched.shutdown(true); log.info("------- Shutdown Complete -----------------"); } public static void main(String[] args) throws Exception { SimpleExample example = new SimpleExample(); example.run(); } }
表达式触发示例
public class SimpleCronExample { public void run() throws Exception { Logger log = LoggerFactory.getLogger(SimpleCronExample.class); log.info("------- Initializing ----------------------"); // 定义调度器 SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); log.info("------- Initialization Complete -----------"); // 获取当前时间的下一分钟 Date runTime = evenMinuteDate(new Date()); log.info("------- Scheduling Job -------------------"); // 定义job JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build(); // 定义触发器,每5秒执行一次 Trigger trigger = newTrigger().withIdentity("trigger1", "group1") .withSchedule(cronSchedule("0/5 * * * * ?")).build(); // 将job注册到调度器 sched.scheduleJob(job, trigger); log.info(job.getKey() + " will run at: " + runTime); // 启动调度器 sched.start(); log.info("------- Started Scheduler -----------------"); // 等待1分钟 log.info("------- Waiting 60 seconds... -------------"); try { Thread.sleep(60L * 1000L); } catch (Exception e) { // } // 关闭调度器 log.info("------- Shutting Down ---------------------"); sched.shutdown(true); log.info("------- Shutdown Complete -----------------"); } public static void main(String[] args) throws Exception { SimpleCronExample example = new SimpleCronExample(); example.run(); } }
时间: 2024-10-02 09:48:31