一、核心(cron表达式)
通过cron表达式可以实现各种复杂的定时任务,具体大家可以到官网查看
这里举个简单例子(” 0/60 * * * * ?“就是60秒执行一次的cron表达式)
二、动态增加调度任务
三、动态删除调度任务
四、注意事项
在任务调度到Job的execute的时候spring自动注入是不会生效的,因为spring框架无法预判你的使用时机,可以采用参数传入方式来解决,当然,看过我前面文章的一定知道,还可以通强行注入的方式解决!!!
五、相关代码
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.CronScheduleBuilder.*;
public class RemindScheduler {
private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
public static void doScheduler(String name , String cron, RoleService roleService, MessageService messageService, UserService userService) throws SchedulerException, InterruptedException {
// 1、创建调度器Scheduler
Scheduler scheduler = schedulerFactory.getScheduler();
// 2、创建JobDetail实例,并与PrintWordsJob类绑定(Job执行内容)
JobDetail jobDetail = JobBuilder.newJob(RemindJob.class)
.withIdentity("job1", "group1").build();
jobDetail.getJobDataMap().put("param", name);
jobDetail.getJobDataMap().put("roleService", roleService);
jobDetail.getJobDataMap().put("messageService", messageService);
jobDetail.getJobDataMap().put("userService", userService);
// 3、构建Trigger实例,每隔1s执行一次
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
.withSchedule(cronSchedule(cron))
.build();
scheduler.scheduleJob(jobDetail, trigger);
scheduler.start();
}
/**
* @Description: 移除一个任务
*
* @param jobName
* @param jobGroupName
* @param triggerName
* @param triggerGroupName
*/
public static void removeJob(String jobName, String jobGroupName,
String triggerName, String triggerGroupName) {
try {
Scheduler sched = schedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
sched.pauseTrigger(triggerKey);// 停止触发器
sched.unscheduleJob(triggerKey);// 移除触发器
sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class RemindJob implements Job {
@Override
public void execute(JobExecutionContext context) {
System.out.println("请关注项目:"+context.getJobDetail().getJobDataMap().get("param"));
}
}