头图

There are two commonly used timing tasks:

  1. Annotation-based
  2. Based on the interface

Based on the annotation @Scheduled


@Service
public class Scheduling1Service {

    //每2秒执行一次(若上次任务执行时间超过2秒,则立即执行,否则从上一个任务开始时算起2秒后执行本次任务)
    @Scheduled(fixedRate = 2000)
    public void test1() throws InterruptedException {
        Thread.sleep(1000L);//模拟定时任务执行耗费了1s
        Thread.sleep(3000L);//模拟定时任务执行耗费了3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test1 is called");
    }

    //上一个任务执行完2秒后,再执行本次任务
    @Scheduled(fixedDelay = 2000)
    public void test2() throws InterruptedException {
        Thread.sleep(3000L);//模拟定时任务执行耗费了3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test2 is called");
    }

    //支持corn表达式
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行
    public void test3() throws InterruptedException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test3 is called");
    }
}
Note: corn who can't write 060fa37c9dd2f0 expressions can use this: https://cron.qqe2.com will automatically generate corn expressions for you, and can detect whether your expressions are legal. perfectly worked!

The above three are used frequently. Because the parameters are not accepted, the main user regularly synchronizes the business scenarios of the third-party basic data.

To use @Scheduled need to reference springboot related dependencies in the pom, and add the @EnableScheduling annotation to the Application main entry function.

Timing task based on interface form

The annotation-based task configuration is very simple and easy to use, but because the parameters cannot be passed, the usage scenarios are limited. Then you need to use timed tasks based on the interface form.

Add dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
@Service
public class Scheduling3Service implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("cccccccc");
                    }
                },
                triggerContext -> {
                    return new CronTrigger("0/1 * * * * ? ").nextExecutionTime(triggerContext);
                }
        );
    }
}

The above are two commonly used timed tasks. Friends, have you lost your studies?

More java original reading: https://javawu.com


大盛玩java
24 声望5 粉丝