首页 > 代码库 > spring时间管理

spring时间管理

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时间管理