Quartz使用小Demo
阿新 • • 發佈:2018-12-03
import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class HelloJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { try { Thread.sleep(5000L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 列印當前的執行時間,格式為2017-01-01 00:00:00 Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("Current Exec Time Is : " + sf.format(date)); System.out.println("Hello World"); } }
import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class HelloScheduler { public static void main(String[] args) throws SchedulerException, InterruptedException { // 列印當前的時間,格式為2017-01-01 00:00:00 Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("Current Time Is : " + sf.format(date)); // 建立一個JobDetail例項,將該例項與HelloJob Class繫結 JobDetail jobDetail = JobBuilder.newJob(HelloJob.class) .withIdentity("myJob").build(); CronTrigger trigger = (CronTrigger) TriggerBuilder .newTrigger() .withIdentity("myTrigger", "group1") .withSchedule( CronScheduleBuilder.cronSchedule("* * * * * ?")) .build(); // 建立Scheduler例項 SchedulerFactory sfact = new StdSchedulerFactory(); Scheduler scheduler = sfact.getScheduler(); scheduler.start(); System.out.println("scheduled time is :" + sf.format(scheduler.scheduleJob(jobDetail, trigger))); //scheduler執行兩秒後掛起 Thread.sleep(2000L); //shutdown(true)表示等待所有正在執行的job執行完畢之後,再關閉scheduler //shutdown(false)即shutdown()表示直接關閉scheduler scheduler.shutdown(false); System.out.println("scheduler is shut down? " + scheduler.isShutdown()); } }