零、废话:
一、maven依赖:
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.3</version> </dependency>
二、Doem:
TimingTaskSchedule需要实现ServletContextListener接口,监听后启动项目时的启动类
package com.thinkgem.jeesite.modules.sys.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class TimingTaskSchedule implements ServletContextListener{ // 服务器启动时执行该事件 @Override public void contextInitialized(ServletContextEvent arg0) { try { QuartzLoad.run(); } catch (Exception e) { e.printStackTrace(); } } // 服务器停止时执行该事件 @Override public void contextDestroyed(ServletContextEvent arg0) { try { QuartzLoad.stop(); } catch (Exception e) { e.printStackTrace(); } } }
这里的 0 0 0 ? * * 表示每天00:00:00执行一次
从左到右分别表示 秒 分 时 日 月 周 年
?表示不关心 *表示每 年可以忽略不写
package com.thinkgem.jeesite.modules.sys.listener; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.Job; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerFactory; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; import com.thinkgem.jeesite.modules.sys.listener.job; public class QuartzLoad { private static Scheduler sched; public static void run() throws Exception { System.out.println("定时任务启动"); JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) job.class) .withIdentity("myjob", "group1").build(); CronTrigger trigger =(CronTrigger) TriggerBuilder.newTrigger() .withIdentity("trigger", "group1") .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 ? * *")) .build(); SchedulerFactory sfact = new StdSchedulerFactory(); Scheduler schedule = sfact.getScheduler(); schedule.start(); schedule.scheduleJob(jobDetail, trigger); } //ֹͣ public static void stop() throws Exception{ sched.shutdown(); } }
Job中就是自己的业务处理
package com.thinkgem.jeesite.modules.sys.listener; import java.text.SimpleDateFormat; import java.util.Date;import org.apache.shiro.authz.annotation.RequiresPermissions; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class job implements Job{ public void execute(JobExecutionContext arg0) throws JobExecutionException { Date date=new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("Time:"+sf.format(date)); System.out.println("Hello"); } } } }
三、web.xml监听:
com.thinkgem.jeesite.modules.sys.listener.TimingTaskSchedule
<listener> <listener-class>com.thinkgem.jeesite.modules.sys.listener.TimingTaskSchedule</listener-class> </listener>
文章来源: quartz定时执行任务,并配置web.xml