博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 定时执行任务
阅读量:6906 次
发布时间:2019-06-27

本文共 2249 字,大约阅读时间需要 7 分钟。

     好不容易写了半天的文章竟然由于断网而丢失了,并未自动保存到草稿箱。只能简单的贴贴代码了。

     

  

package com.dong.schedule;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class ScheduleTask {		 @Scheduled(cron="*/5 * * * * ?")	    public void demoServiceMethod()	    {	        System.out.println("ScheduleTask   "+Thread.currentThread()+"   Method executed at every 5 seconds. Current time is :: "+ new Date());	    }	 @Scheduled(cron="*/3 * * * * ?")	    public void sayHi()	    {	        System.out.println("ScheduleTask   "+Thread.currentThread()+"   Method executed at every 3 seconds. Current time is :: "+ new Date());	    }}

  

package com.dong.schedule;import java.util.Date;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;import org.springframework.scheduling.support.CronTrigger;import org.springframework.stereotype.Component;/*** * 代码中动态设置cron表达式的方式。 */@Componentpublic class MyTask {	@Autowired	private ThreadPoolTaskScheduler myScheduler;		public void run(){		//此处可以动态设置		myScheduler.schedule(new MySchedulerTask(), new CronTrigger("*/2 * * * * ?"));	}		private class MySchedulerTask implements Runnable{		@Override		public void run() {			// TODO Auto-generated method stub			 System.out.println("MyTask"+Thread.currentThread()+"   Method executed at every 2 seconds. Current time is :: "+ new Date());		}			}			}

  

import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {	public static void main(String[] args) {          ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");          MyTask myTask = (MyTask) context.getBean("myTask");        myTask.run();    }  }

  参考的资料 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

  http://howtodoinjava.com/spring/spring-core/4-ways-to-schedule-tasks-in-spring-3-scheduled-example/

  http://blog.csdn.net/lmj623565791/article/details/27109467

转载于:https://www.cnblogs.com/dongqiSilent/p/5170324.html

你可能感兴趣的文章
ES6整理
查看>>
Q438 找到字符串中所有字母异位词
查看>>
图论-BFS解无权有向图最短路径距离
查看>>
文件排序合并
查看>>
程序实践系列(九)多态性和虚函数
查看>>
ls -lrt
查看>>
读取Excel是数据截断问题
查看>>
Linux下Fork与Exec使用
查看>>
在 Java 的反射中,Class.forName 和 ClassLoader 的区别
查看>>
武汉科技大学ACM :1007: 华科版C语言程序设计教程(第二版)习题5.7
查看>>
Java基础
查看>>
MongoDB(课时20 游标)
查看>>
个人项目1——自动生成四则运算
查看>>
COBBLER无人值守安装
查看>>
时间--》梅叔叔
查看>>
如何从dvi生成pdf--------亲测有效果.
查看>>
天天洗一次澡还真是好方法
查看>>
validator的验证
查看>>
python的for循环、while循环
查看>>
就算神游 之四:富士山和富士游乐园 2
查看>>