SpringBoot定时器定时调度

如何使用

SpringBoot本身已经为我们提供了内置的定时器Scheduled,我们直接使用即可。

@Configuration
@EnableScheduling
public class SchedulingConfig {

    @Scheduled(cron = "0 0/1 * * * ?")
    public void test(){
        System.out.println("定时调度。。。。。。。。。。。。");
    }
}

@Sheduled注解

Cron属性——String

Seconds (秒): 可出现", - * /"四个字符,有效范围为0-59的整数
Minutes (分): 可出现", - * /"四个字符,有效范围为0-59的整数
Hours (时): 可出现", - * /"四个字符,有效范围为0-23的整数
DayofMonth (天/月): 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
Month (月): 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
DayofWeek (星期几): 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
Year (年): 可出现", - * /"四个字符,有效范围为1970-2099年
推荐一个cron表达式自动生成的网站 点击获取

fixedRate属性——Long

表示多长时间执行一次,单位为ms(毫秒),后执行

fixedDelay属性——Long

表示多长时间执行一次,单位为ms(毫秒),先执行fixedRate与fixedDelay不同在于启动时先走定时器fixedRate后执行代码块,而fixedDelay先执行代码块,后执行定时器,通过以下代码来演示

@Configuration
@EnableScheduling
public class SchedulingConfig {

    @Scheduled(fixedRate = 10000)
    public void test1() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("定时任务1================");
    }

    @Scheduled(fixedRate = 10000)
    public void test2() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("定时任务2================");
    }
}

启动application,输出结果为

定时任务2================
定时任务1================
定时任务2================
定时任务1================

initialDelay属性——Long

该属性表示第一次执行延时的时间,只针对第一次执行有效

猜你喜欢

转载自blog.csdn.net/qq_21046665/article/details/79684226
今日推荐