Spring Task定时任务

在工作中有用到spring task作为定时任务的处理,spring通过接口TaskExecutor和TaskScheduler这两个接口的方式为异步定时任务提供了一种抽象。spring自身也提供了一种定时任务的实现:springtask。spring task支持线程池,可以高效处理许多不同的定时任务。同时,spring还支持使用Java自带的Timer定时器和Quartz定时框架。
 

TaskExecutor继承Executor,为定时任务的执行提供线程池的支持。

TaskScheduler提供定时任务支持,需要传入一个Runnable的任务做为参数,并指定需要周期执行的时间或者触发器,这样Runnable任务就可以周期性执行了。

  java代码:

          注解形式:注解@Scheduled(cron="/5 * * * * *")

package com.spring.quartz.quartz;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @author cst
 * @site www.xiaomage.com
 * @company xxx公司
 * @create 2019-02-23 16:01
 */
@Service
public class SpringTask {

    //spring Task的定时任务
//    spring task是单线程的,(当上一个定时任务没有结束的时候,他不会调用新的定时任务)
    @Scheduled(cron = "0/5 * * * * *")
    public void tast(){
        System.out.println("spring task====");
        try {
            Thread.sleep(10*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("spring task结束-----");

    }



}

测试代码:

       注解:@EnableScheduling是spring自带定时任务功能,与@Scheduled一起使用

package com.spring.quartz;

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

@EnableScheduling
@SpringBootApplication
public class QuartzApplication {

    public static void main(String[] args) {
        SpringApplication.run(QuartzApplication.class, args);
    }

}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值