@Scheduled 定時器 cron表達式自定義配置

方法一:java

<context:annotation-config />    
<!--spring掃描註解的配置   -->    
<context:component-scan base-package="com.baodian.bdweb.timer" />   
      
<bean id="Taskaa" class="com.baodian.bdweb.timer.Taskaa" />    
<bean id="Taskbb" class="com.baodian.bdweb.timer.Taskbb" />    
<task:scheduled-tasks>    
     <task:scheduled ref="Taskaa" method="show" cron="01 38 15 * * ?" />    
     <task:scheduled ref="Taskbb" method="show" cron="01 39 15 * * ?" />   
</task:scheduled-tasks>  web

--------------------- spring

@Component("Taskaa")  
public class Taskaa{  
      
    @Scheduled  
    public void show(){  
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        System.out.println("Taskaa:"+s.format(new Date()));    
    }  
}  
--------------------- 
@Component("Taskbb")  
public class Taskbb{  
      
    @Scheduled  
    public void show(){  
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        System.out.println("Taskbb:"+s.format(new Date()));    
    }  
}  
--------------------- ide

方法二:component

<!-- 計劃任務配置,用 @Service @Lazy(false)標註類,用@Scheduled(cron = "0 0 2 * * ?")標註方法 -->
<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" />
package com.hhwy.fm.statisticalanalysis.subcontractproduction.job;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.util.*;
 
@Component
public class SubcontractProductionJob implements SchedulingConfigurer {
     
    //設置任務執行時間輪轉,cronExpression表達式 (秒 分 時 日 月 周)
    @Value("${TASK_DYNAMIC_CRON}")
    private String dynamicCron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
               //業務邏輯處理
                
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger trigger = new CronTrigger(dynamicCron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }

 }
相關文章
相關標籤/搜索