First, the differences between the two methods are briefly described:

The advantage of annotation is that it is simple and convenient, but the disadvantage is that the execution cycle is fixed and cannot be changed dynamically. The interface can be implemented by saving cron expressions to the database and reading from the database to vary the execution time.

@Scheduled Implements Scheduled tasks

Note that cron in @Scheduled only has 6 fields

package com.demo.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class StaticTask{

    @Scheduled(cron = "0/5 * * * *?")
    public void doTask(){
        System.out.println("Scheduled task executes every 5 seconds:"+LocalDateTime.now()); }}Copy the code

SchedulingConfigurer implements scheduled tasks on the interface

To implement a scheduled task by implementing an interface re-method, @enablesCheduling is required on the task class or startup class

The demo code is a table that has a CRon table that has a crON expression set up. Dynamic Settings by querying. Rewrite method is this class to scheduledTaskRegistrar. The actual implementation addTriggerTask (Runnable task, Trigger the Trigger) task: you need to perform the task, Essentially a thread trigger: executes cron expressions

CronExpression. IsValidExpression (cron) check the legitimacy of the cron expression, is a kind of quartz need extra dependence, this check is not a must.

Rely on:

< the dependency > < groupId > org. Quartz - the scheduler < / groupId > < artifactId > quartz < / artifactId > < version > 2.3.0 < / version > </dependency>Copy the code

Test code:

package com.demo.schedule;

import com.demo.mapper.CronMapper;
import com.demo.pojo.Cron;
import org.quartz.CronExpression;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;


@Configuration
public class TestTask implements SchedulingConfigurer {
    private CronMapper cronMapper;

    public TestTask(CronMapper cronMapper) {
        this.cronMapper = cronMapper;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() -> {
            System.out.println("Implement interface mode:" + LocalDateTime.now());
        }, triggerContext -> {
            Cron c = cronMapper.selectByPrimaryKey(1);
            String cron = c.getCron();
            if(! CronExpression. IsValidExpression (cron)) {/ / cron = 10 seconds by default"0/10 * * * *? ";
            }
            returnnew CronTrigger(cron).nextExecutionTime(triggerContext); }); }}Copy the code