1. Introduce Quartz dependency
2. Add @EnableScheduling annotation to the SpringBoot startup class
3. Create a scheduled task work class in the method, the code is as follows:
package com.jlzh.lftwebservice.service.quartz;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @ClassName: QuartzJob
* @ Description: 定时任务类
* @author:
* @date:2022/11/02
*/
@Component
public class QuartzJob{
@Scheduled(cron = "0/5 * * * * ? ")
protected void executeInternal() throws JobExecutionException {
String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
System.out.println(time + "===> 正在工作。。。");
}
}
At this point, it should be noted that the class where the scheduled task is located must be managed by the Spring container. The easiest way is to add the @Component annotation to the class. Adding the @Scheduled(cron = "0/5 * * * * ? ") annotation to the scheduled task working method indicates that the task is executed every 5 seconds.
4. The execution result is shown in the screenshot:
5. The value of cron can also be specified in the form of an external configuration file, the code is as follows:
package com.jlzh.lftwebservice.service.quartz;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @ClassName: QuartzJob
* @ Description: 定时任务类
* @author:
* @date:2022/11/02
*/
@Component
public class QuartzJob{
@Scheduled(cron = "${cron.exp}")
protected void executeInternal() throws JobExecutionException {
String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
System.out.println(time + "===> 正在工作。。。");
}
}
Then fill in the value of the configuration variable in the configuration file application.yml. This method is more flexible, and the time can be changed without modifying the code. And if the value is changed to "-", it means that the scheduled task is invalid.
After the value is changed to "-", it means that the scheduled task is invalid. If you use "-" directly, it will be marked in red, and you can quote it with single quotation marks.