1. 程式人生 > >Spring的定時任務(任務排程)

Spring的定時任務(任務排程)

一、XML配置方式

第1步、編寫類

/**
 * 定時計算
 */
@Component("profitScheduler")
public class ProfitScheduler {	

	@Autowired
	private XXXService  xxxService;		

	public void execute() {
		logger.info("start 執行定時任務");
		try {
				xxxService.testMethod();
		} catch (Exception e) {
			logger.error("執行異常。{}",e);
			e.printStackTrace
(); } logger.info("end 執行定時任務"); } }

第2步、 編寫spring-scheduler.xml 配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<task:scheduled-tasks scheduler="scheduler" > <task:scheduled ref="profitScheduler"
method="execute" cron="0 0/2 * * * ?" />
</task:scheduled-tasks> <task:scheduler id="scheduler" pool-size="5" /> </beans>

第3步、引入spring-scheduler.xml檔案:

spring.xml中引入spring-scheduler.xml檔案:

<import resource="classpath*:spring-scheduler.xml"/>

二、註解方式

第1步:

import org.springframework.scheduling.annotation.Scheduled;    
import org.springframework.stereotype.Component;  
  
@Component(“taskJob”)  
public class TaskJob { 

    @Scheduled(cron = "0 0 3 * * ?")  
    public void job1() {  
        System.out.println(“任務進行中。。。”);  
    } 
}

第2步:

spring.xml配置檔案開啟task:

<task:annotation-driven/>