SpringMVC、SpringBoot的定时任务

SpringMVC、SpringBoot的定时任务

SpringMVC定时任务

首先在SpringMVC.xml的配置如下:

  1. 在xmlns中添加 xmlns:task=“http://www.springframework.org/schema/task”
  2. 在xsi中添加
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.2.xsd
  3. 单个定时任务的配置 (comm.demo.task是定时任务所在的包名)
    task:annotation-driven/
    <context:component-scan base-package=“comm.demo.task” />
  4. 多个定时任务的配置
    <task:executor id=“executor” pool-size=“10”/>
    <task:scheduler id=“scheduler” pool-size=“10”/>
    <task:annotation-driven scheduler=“scheduler” executor=“executor” proxy-target-class=“true”/>
    <context:component-scan base-package=“comm.demo.task” />

需要引用的java类

org.springframework.scheduling.annotation.Scheduled;
org.springframework.stereotype.Component;

定时任务实例

/**
 * 
 * 类名称:TimerTask   
 * 类描述:定时器任务
 *
 */
@Component
public class TimerTask {
  /**
   * 每天22点30启动任务
   */
  @Scheduled(cron = "0 30 22 ? * *")
  public void test1()
  {
      System.out.println("job1 开始执行..."+TimeUtils.getTime());
  } 
     @Scheduled(cron = "0/5 * * * * ?")//每隔5秒隔行一次 
  public void test2()
  {
     System.out.println("job2 开始执行");
  } 
}

SpringBoot定时任务

@Scheduled配置方式

配置实例如下
@EnableScheduling
@Component
public class Task {
@Scheduled(cron = “0/5 * * * * *”)
public void scheduled() {
System.out.println(“使用cron {}”+ System.currentTimeMillis());
}

@Scheduled(fixedRate = 5000)
public void scheduled1() {
    System.out.println("使用fixedRate{}"+System.currentTimeMillis());
}

}
*说明
1.添加 @EnableScheduling 注解,既是开启定时任务
2.首先使用 @Scheduled 注解开启一个定时任务。
fixedRate 表示任务执行之间的时间间隔,具体是指两次任务的开始时间间隔,即第二次任务开始时,第一次任务可能还没结束。
fixedDelay 表示任务执行之间的时间间隔,具体是指本次任务结束到下次任务开始之间的时间间隔。
initialDelay 表示首次任务启动的延迟时间。
所有时间的单位都是毫秒。

cron 表达式 说明

字段名

 

允许的值

 

允许的特殊字符

 

0-59

 

, - * /

 

0-59

 

, - * /

小时

 

0-23

 

, - * /

 

1-31

 

, - * ? / L W C

 

1-12 or JAN-DEC

 

, - * /

周几

 

1-7 or SUN-SAT

 

, - * ? / L C #

年 (可选字段)

 

empty, 1970-2099

 

, - * /

举例说明
“0 0 12 * * ?” 每天中午十二点触发
“0 15 10 ? * *” 每天早上10:15触发
“0 15 10 * * ?” 每天早上10:15触发
“0 15 10 * * ? *” 每天早上10:15触发
“0 15 10 * * ? 2005” 2005年的每天早上10:15触发
“0 * 14 * * ?” 每天从下午2点开始到2点59分每分钟一次触发
“0 0/5 14 * * ?” 每天从下午2点开始到2:55分结束每5分钟一次触发
“0 0/5 14,18 * * ?” 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
“0 0-5 14 * * ?” 每天14:00至14:05每分钟一次触发
“0 10,44 14 ? 3 WED” 三月的每周三的14:10和14:44触发
“0 15 10 ? * MON-FRI” 每个周一、周二、周三、周四、周五的10:15触发
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值