SpringBoot定时任务Schedule (七)

在日常项目运行中,我们总会有需求在某一时间段周期性的执行某个动作。比如每天在某个时间段导出报表,或者每隔多久统计一次现在在线的用户量。在springboot中可以有很多方案去帮我们完成定时器的工作,有Java自带的java.util.Timer类,也有强大的调度器Quartz,还有SpringBoot自带的Scheduled,今天主要说说Scheduled。

定时器比较

框架名称Cron表达式固定间隔执行固定频率执行任务持久化难易度
TimerTask不支持支持支持不支持一般
schedule支持支持支持不支持简单
Quartz支持支持支持支持

在实际应用中,如果没有分布式场景(quartz 支持分布式, schedule 不支持(需要自己实现,用分布式锁),schedule跟spring结合的更好,还是很适用的。

创建schedule工程

使用IntelliJ IDEA创建helloschedule

SpringBoot(九)定时任务Schedule

SpringBoot(九)定时任务Schedule

SpringBoot(九)定时任务Schedule

SpringBoot(九)定时任务Schedule

SpringBoot(九)定时任务Schedule

点击finish完成项目的创建。

SpringBoot(九)定时任务Schedule

为了方便演示,使用@Slf4j输出日志,添加lombok引用,@Slf4j不清楚的可以看看SpringBoot(八)配置logback日志

添加export类。

package com.task.log;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by toutou on 2018/10/20.
 */
@Component
@Slf4j
public class export {
    @Scheduled(cron = "0 0/1 * * * ?")
    public void minuteExport(){
        log.debug("每分钟执行一次的任务:" + getDate());
    }

    @Scheduled(fixedRate = 5000)
    public void fiveSecondExport(){
        log.debug("每5秒执行一次:" + getDate());
    }

    @Scheduled(cron = "0/2 * * * * ?")
    public void twoSecondExport(){
        log.debug("每2秒执行一次:" + getDate());
    }

    @Scheduled(cron = "0 55 14 ? * *")
    public void regularTimeExport(){
        log.debug("每天上午14点55分执行:" + getDate());
    }

    private String getDate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}

启动类中添加@EnableScheduling注解,然后运行。

SpringBoot(九)定时任务Schedule

查看IntelliJ IDEA控制台日志和物理文件日志

SpringBoot(九)定时任务Schedule

SpringBoot(九)定时任务Schedule

如上图,简单的定时任务输出日志搭建完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值