Java实现定时任务

1.单线程定时任务

@Component。
@EnableScheduling   // 开启定时任务
public class SaticScheduleTask {
    //添加定时任务
    @Scheduled(cron = "0/10 * * * * ?")
    //或直接指定时间间隔,例如:10秒
    //@Scheduled(fixedRate=10000)
    private void configureTasks() {
        System.err.println("执行定时任务时间: " + LocalDateTime.now());
    }
}

Cron表达式:
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为:
秒(0~59)
分钟(0~59)
3 小时(0~23)
4 天(0~31)
5 月(0~11)
6 星期(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
年份(1970-2099)
在线cron表达式生成:http://qqe2.com/cron/index

2.多线程定时任务

@Component  //表明该类是一个配置类 
@EnableScheduling  // 开启定时任务
@EnableAsync //开启异步事件的支持
public class MyTimingTasks {

    @Async
//    @Scheduled(fixedDelay = 1000)  //间隔1秒
    @Scheduled(cron = "0 11 17 1/1 * ? ")   //当前表达式为每天下午17:11分执行
    public void first() throws InterruptedException {
        System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
        System.out.println();
    }

    @Async
    @Scheduled(fixedDelay = 2000)
    public void second() {
        System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
        System.out.println();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值