Spring Boot创建定时任务

博客介绍了在启动类添加@EnableScheduling注解开启定时任务,详细讲解了@Scheduled注解的参数,如cron用表达式设置、zone为时区、fixedDelay等按时间间隔执行、initialDelay延迟执行等,还提及因不难仅举两例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在启动类加上@EnableScheduling注解

package com.dfyang;

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

@SpringBootApplication
//开启定时任务
@EnableScheduling 
public class SchedulerApplication {

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

}

@Scheduled注解的参数详解

  • cron:使用cron表达式
  • zone:时区,默认即可
  • fixedDelay:按时间间隔执行
  • fixedDelayString:按时间间隔执行,只不过输入的字符串
  • fixedRate:按多少秒执行
  • fixedRateString:按多少秒执行,只不过输入的字符串
  • initialDelay:延迟多少秒执行第一次定时任务
  • initialDelayString:延迟多少秒执行第一次定时任务,只不过输入的字符串
由于并不难,所以只举了两个例子。

fixedRate:按多少秒执行

package com.dfyang.scheduler;

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

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SchedulerTask {

    private static final SimpleDateFormat sdf =
    					 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 1s钟执行一次
     * @return
     */
    @Scheduled(fixedRate = 1000)
    public void printCurrentTime() {
        System.out.println(sdf.format(new Date()));
    }
}

在这里插入图片描述
Cron:使用cron表达式

package com.dfyang.scheduler;

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

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SchedulerTask {

    private static final SimpleDateFormat sdf =
    						 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 每分钟的0s、10s、20s、30s、40s、50s执行一次
     * @return
     */
    @Scheduled(cron = "0,10,20,30,40,50 * * * * ?")
    public void printCurrentTime() {
        System.out.println(sdf.format(new Date()));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值