SpringBoot中,创建定时任务

在Spring Boot中,定时任务可以使用@Scheduled注解来实现。要使用@Scheduled注解,你需要确保以下几个步骤:

启用定时任务功能

在Spring Boot应用的主类上添加@EnableScheduling注解:

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

@SpringBootApplication
@EnableScheduling
public class ScheduledTasksApplication {

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

创建定时任务方法

在一个Spring管理的bean(例如一个Service类)中创建定时任务方法,并使用@Scheduled注解:

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

@Service
public class ScheduledTaskService {

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("Current time is: " + new java.util.Date());
    }
}

在这个示例中,reportCurrentTime方法每隔5秒钟执行一次。@Scheduled注解可以接受多种配置参数:

  • fixedRate:以固定的时间间隔执行任务(以毫秒为单位)。
  • fixedDelay:在前一次调用完成后等待固定的时间间隔再执行任务(以毫秒为单位)。
  • initialDelay:在应用启动后等待固定的时间再首次执行任务(以毫秒为单位)。
  • cron:使用cron表达式来控制任务执行的时间。
使用cron表达式

你可以使用cron表达式更灵活地控制任务的执行时间。例如,每天晚上10点执行任务:

@Scheduled(cron = "0 0 22 * * ?")
public void scheduledTaskUsingCron() {
    System.out.println("Task executed at 10 PM");
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值