Springboot 实现定时任务

在实际开发过程中,经常遇到需要用到定时任务的场景,一种是在固定的时间点执行某个任务,比如每天0点执行任务;另一种是延迟执行任务,比如在某方法运行后过20分钟以后执行任务,可以用在临时数据的删除等场景。这里简单介绍两种场景下的定时任务实现方法。

一. 定时执行

1. 在你的Spring Boot应用程序的主类上添加@EnableScheduling注解,以启用定时任务的支持

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

@SpringBootApplication
@EnableScheduling
public class YourApplication {

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

2. 创建一个带有定时任务方法的类,并在该方法上添加@Scheduled注解来指定任务的执行时间。

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

@Component
public class MyScheduledTasks {

    @Scheduled(fixedRate = 5000) // 每隔5秒执行一次任务
    public void myTask1() {
        // 执行你的定时任务逻辑
        System.out.println("定时任务执行中...");
    }

    @Scheduled(cron = "0 0 0 * * ?") // 每天0点执行任务
    public void myTask2() {
        // 执行你的定时任务逻辑
        System.out.println("定时任务执行中...");
    
}

使用@Scheduled注解的cron属性来指定Cron表达式,Cron表达式的语法如下:

秒 分 时 日 月 周 年(可选)

其中,*表示任意值,?表示不指定,0 0 0 * * ?表示每天的0点。

二. 延时执行

1. 创建一个TimeTask实例继承Runnable接口,重写run方法。

import javax.annotation.Resource;

public class TimeTask implements Runnable{

    @Resource
    private TaskExample taskExample;

    private String message;

    public TimeTask(String message) {
        this.message = message;
    }

    @Override
    public void run() {
        taskExample.sayHello();
        System.out.println(message);
    }
}

TaskExample 类即为需要定时执行的目标方法所在的类:

import org.springframework.stereotype.Service;

@Service
public class TaskExample {

    public void sayHello() {
        System.out.println("Hello!");
    }

}

2. 在服务类中注入TaskScheduler,实现定时任务。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;

import java.time.Instant;

@Service
public class TimeTaskService {

    @Autowired
    private TaskScheduler taskScheduler;

    public void test() {
        System.out.println("start");
        TimeTask timeTask = new TimeTask("end");
        taskScheduler.schedule(timeTask, Instant.now().plusSeconds(20)); //20秒后执行任务
    }

}

需要延迟多久根据需求自己设定 Instant.now() 的值就行了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值