cron表达式格式:
{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
* 表示所有值
? 表示未说明值,即不关心何值
L 表示每月最后一天
/ 表示每次递增的值
- 表示一个指定的范围
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
定义一个定时任务
package com.example.demo.job;
import org.quartz.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author : sheep669
* @description : TODO
* @created at 2022/10/5 10:19
*/
public class HelloJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDetail jobDetail = jobExecutionContext.getJobDetail();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
System.out.println(jobDataMap.get("depart") + "----" + jobDataMap.get("username") + "现在时间是:" + time.format(new Date()));
}
}
定义触发器
package com.example.demo.trigger;
import com.example.demo.job.HelloJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
/**
* @author : sheep669
* @description : TODO
* @created at 2022/10/5 10:28
*/
public class TriggerRunner {
public static void main(String[] args) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob", "group1")
.usingJobData("username", "张三")
.build();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("depart", "销售部");
SimpleTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
//执行一次
.withIntervalInSeconds(2).withRepeatCount(0))
.build();
StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = stdSchedulerFactory.getScheduler();
scheduler.scheduleJob(jobDetail, trigger);
scheduler.start();
}
}
启动主方法即可