Java和SpringBoot如何使用定时任务(干货!!)

Java定时任务

一、Java原生定时任务

使用 java.util.Timerjava.util.TimerTask 类来创建传统的 Java 定时任务

public class JavaTimerTask {
    //多线程并行处理定时任务时,Timer运行多个TimeTask时,只要其中之一没有捕获抛出的异常,其它任务便会自动终止运行,使用ScheduledExecutorService则没有这个问题。
    public static void main(String[] args) {
        Timer timer = new Timer();
        // 延迟1秒后开始执行任务,每隔2秒执行一次
        timer.schedule(new JavaTask(), 1000, 2000);
    }

    //继承接口 TimerTask
    static class JavaTask extends TimerTask {
        @Override
        public void run() {
            LocalDateTime now = LocalDateTime.now();
            int second = now.getSecond();
            if (second >= 50) {
                throw new RuntimeException("定时任务发生异常");
            }
            System.out.println("Java原生定时任务: " + now);
        }
    }
}

二、SpringBoot定时任务

在启动类上加上 @EnableScheduling 注解

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

@SpringBootApplication
@EnableScheduling
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

使用与 Spring 相同的 @Scheduled 注解来定义定时任务

@Component
public class SpringBootTimerTask {

    @Scheduled(initialDelay = 1000, fixedRate = 2000) // 延迟1秒后开始执行任务,每隔2秒执行一次
    public static void run() {
        LocalDateTime now = LocalDateTime.now();
        int second = now.getSecond();
        if (second >= 50) {
            System.out.println("定时任务发生异常: " + now);
            throw new RuntimeException("定时任务发生异常");
        }
        System.out.println("Java原生定时任务: " + now);
    }

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨小羊-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值