SpringBoot使用注解形式定时执行同步任务

1、SpringBoot定时执行同步任务可以使用org.springframework.scheduling包下的@EnableScheduling以及@Scheduled注解来实现,代码如下:


@Configuration
@EnableScheduling

public class SynchTask {

    @Scheduled(cron = "0 */1 *  * * * ")
    public void myTask() {

        try {
            Thread.sleep(1000 * 60);
            System.out.println(" Tasks Examples By Cron: The time is now " + dateFormat().format(new Date()));
        }
        catch (InterruptedException e) {

            e.printStackTrace();
        }
        System.out.println();
    }

    private SimpleDateFormat dateFormat() {
        return new SimpleDateFormat("HH:mm:ss");
    }

}

@EnableScheduling 注解在类上,定义这是一个定时执行类,@Scheduled在执行方法上,@Configuration注解会在springBoot启动时,将该类加载至spring容器中;cron = "0 */1 *  * * * ",cron表达式表示每分钟执行一次,Thread.sleep(1000 * 60);表示业务执行时间,运行实际结果是每2分钟执行一次,说明@EnableScheduling, @Scheduled注解是同步执行的

执行结果如下:

SpringBoot使用注解形式定时执行同步任务_第1张图片

你可能感兴趣的:(SpringBoot使用注解形式定时执行同步任务)