Spring3.0未来独立开发的计时任务工具,spring-task,您可以将其与轻量级Quartz并且使用非常简单,spring在相关包之外不需要其他包,并且支持注释和概要文件。
第一:基于注释
1、spring.xml在相应的位置加入。
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
定时任务开关
此外,注释扫描是必须的。
2,任何测试类

@Component
public class MyTask {
@Scheduled(cron = "0/3 * * * * ?")
public void myjob() {
System. out.println( "task execing ...");
}

第二:基于xml配置
1,添加到上述基于注释的配置中。
(bean路径指向定时任务执行类)


2,任何测试类

public class TaskJob {
void show(){
System. out.println( "5s 执行一次。。。。" );
}
void print(){
System. out.println( "10s 执行一次。。。。" );
}
}

【注意】
有两种测试方法
1,已配置启动sping项目
2、

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
}

通过这种方式,我一直在表明找不到该类。
可以使用以下方法解决:
1.加上classpath:前缀
ApplicationContext ctx=new FileSystemXmlApplicationContext("classpath:applicationContext.xml";
2.加上file:写入整个路径
ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext ctx=new ClassPathXmlApplicationContext("file:F:/workspace/SpringExercis/src/applicationContext.xml");
如果这只是一个测试,最简单的方法就是进行测试。xml放在src下方便
【附】
关于cron表达,如果不理解?它很容易被错误地使用。
1) 每个位代表 [ 秒 分 时 日 月 周 年]
2) The ? character is allowed for the day-of-month and day-of-week fields. It is used to specify no specific value. This is useful when you need to specify something in one of the two fields, but not the other.
> 注意两个概念 day-of-month /day-of-week

CRON表达式 含义
"0 0 12 * * ?" 每天中午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触发
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除