spring定时器

本文介绍了使用Spring框架中的定时任务调度机制,包括基于固定延迟(fixedDelay)和固定频率(fixedRate)的任务执行方式,并展示了如何利用Cron表达式实现更复杂的定时任务需求。此外,还提供了动态调整Cron表达式的实例。

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

1、每隔10s执行一次,基准是上批次执行完成,也就是要等待上个任务执行完成,下个任务10s后执行

     @Scheduled(fixedDelay = 10000)
        public void doSomething() { 

              //TODO
        }

2、每隔10s执行一次,基准是上批次开始执行,也就是不等待,每10s一个执行窗口

     @Scheduled(fixedRate = 10000)
        public void doSomething() { 

              //TODO
        }

3、cron,比较常用

     @Scheduled(cron = "0 1 0 * * ?")

4、动态变更cron

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ScheduledFuture;

@RestController("/")
public class TimerTest {

    private ScheduledFuture<?> future;
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @RequestMapping("/start")
    public String start(@RequestParam String time) {
        this.stop();
        future = threadPoolTaskScheduler.schedule(() -> System.out.println("-=-=-=-=-="), new CronTrigger("0 0/" + time + " * * * ? "));
        System.out.println("start");
        return "start";
    }

    public String stop() {
        if (null != future) {
            future.cancel(true);
        }
        System.out.println("stop");
        return "stop";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值