springboot任务之定时任务

时间:2022-11-30 18:56:58

springboot任务之定时任务

1-service包下新建ScheduleService类

package com.example.springboottask.service;

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

@Service
public class ScheduleService {

    /**
     *   A cron-like expression, extending the usual UN*X definition to include triggers
     * 	  on the (second, minute, hour, day of month, month, and day of week).
     * 	  一共6位
     * 	  0 * * * * MON-FRI     从周一到周五的每一分钟执行一次
     * 	  * * * * * MON-SAT     从周一到周六的每一秒执行一次
     */
    @Scheduled(cron = "0 * * * * MON-FRI")
    public void hello(){
        System.out.println("hello...");
    }
}

2-启动类中添加@EnableScheduling注解

package com.example.springboottask;

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

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

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

}

3-运行

周一到周五整分钟打印hello...

springboot任务之定时任务

4-cron表达式特殊字符--枚举

springboot任务之定时任务

springboot任务之定时任务

步长

springboot任务之定时任务

springboot任务之定时任务