1. 程式人生 > >spring時間管理

spring時間管理

utf-8 enc ack lns enables cati out nco 無需

spring時間管理相比Quartz要簡單的多,但功能不如quartz強大

spring.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation
=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="task"/> </beans
>

要執行的任務

package task;

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

/**
 * Created by MY on 2017/8/7.
 */
@Service
public class TaskService {
    //每三秒執行一次
    @Scheduled(cron ="0/3 * 17 * * ?")
    public void print(){
        System.out.println(
"spring任務"); } }

啟用任務調動

package task;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * Created by MY on 2017/8/7.
 */
@Configuration
@EnableScheduling
//啟用任務調動
public class TaskConfig {
}

讀取spring.xml文件即可,無需做其他操作

package task;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by MY on 2017/8/7.
 */
public class SpringTask {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext cxt=new ClassPathXmlApplicationContext("spring.xml");
    }
}

執行結果

spring任務
spring任務
spring任務
spring任務

spring時間管理