springboot任务之定时任务

本文详细介绍了如何在SpringBoot项目中配置和使用基于注解的定时任务,包括创建ScheduleService类,添加@EnableScheduling注解至启动类,以及cron表达式的理解和应用。

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...

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

步长

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值