spring boot—定时任务

开启定时任务

在程序入口类中添加@EnableScheduling注解

package com.alibaba;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
@EnableAsync
@RestController
@SpringBootApplication
@EnableCaching
@EnableScheduling
@MapperScan("com.alibaba.dao")
public class TmallApplication {
 
	public static void main(String[] args) {
		SpringApplication.run(TmallApplication.class, args);
	}
 
	@RequestMapping(value = "hello",method = RequestMethod.GET)
	public String getHello(){
		return "hello world";
	}
}

创建定时任务

单独创建一个类,用来存放定时任务,然后在每个定时任务方法上,用注解标明定时任务的执行周期。我这里以每间隔10秒打印一下当前系统时间为例。

package com.alibaba.task;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
public class ScheduledTask {
    private final Logger logger = LoggerFactory.getLogger(getClass());
 
    /**
     * 每间隔10秒输出时间
     */
    @Scheduled(fixedRate = 10000)
    public void logTime(){
        logger.info("定时任务,现在时间:"+System.currentTimeMillis());
 
    }
}

@Scheduled的几种用法

  1. @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
  2. @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
  3. @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
  4. @Scheduled(cron="*/5 * * * * *") :通过cron表达式定义规则
  5. 注意,这里的时间,单位是毫秒,1秒=1000毫秒

运行项目

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值