260_定时任务


源码查看

image.png
image.png
image.png

TaskScheduler 任务调度者

TaskExecutor 任务执行者

创建项目

image.png
image.png

开启定时任务注解功能 @EnableScheduling

@EnableScheduling // 开启定时任务注解功能
package com.qing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling // 开启定时任务注解功能
@EnableAsync // 开启异步注解功能
@SpringBootApplication
public class Springboot10TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot10TaskApplication.class, args);
    }

}

使用测试 @Scheduled

cron表达式

image.png

package com.qing.service;

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

import java.time.LocalDateTime;

@Service
public class ScheduledService {

    // cron表达式:秒 分 时 日 月 周
    // ?代表不确定,只有日和周使用,互为问号,日为*或数字时,周不确定为?,周为*或数字时,日不确定为?
    // 每2秒执行一次
    @Scheduled(cron = "0/2 * * * * ?")
    public void hello() {
        System.out.println("hello,执行成功" + LocalDateTime.now().toString());
    }
}

image.png

posted @ 2022-02-09 17:10  清风(学习-踏实)  阅读(27)  评论(0编辑  收藏  举报