zoukankan      html  css  js  c++  java
  • SchedulerServletContextListener定时器的使用配置

    SchedulerServletContextListener的定时器配置,取自于tomcat的时间listener,于是就有了web.xml的配置

      <listener>
        <listener-class>com.aneop.common.scheduler.SchedulerServletContextListener</listener-class>
      </listener>

    通过<listenner-class>可以找到指定的定时器的java类,调用ServletContextListener接口。

    定时器的初始化与断开

    public class SchedulerServletContextListener implements ServletContextListener {
        private static String SCHEDULER = "cron4j.scheduler";
        
        public void contextInitialized(ServletContextEvent event) { 
            ServletContext context = event.getServletContext();
            // 1. Creates the scheduler.
            Scheduler scheduler = new Scheduler();
            // 2. Registers a custom task collector.
            TaskCollector collector = new MyTaskCollector();
            scheduler.addTaskCollector(collector);
            // 3. Starts the scheduler.
            scheduler.start();
            // 4. Registers the scheduler.
            context.setAttribute(SCHEDULER, scheduler);
        }
    
        public void contextDestroyed(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            // 1. Retrieves the scheduler from the context.
            Scheduler scheduler = (Scheduler) context.getAttribute(SCHEDULER);
            // 2. Removes the scheduler from the context.
            context.removeAttribute(SCHEDULER);
            // 3. Stops the scheduler.
            scheduler.stop();
        }

     然后定义我们自己的任务收集器MyTaskCollector(),继承TaskCollector,并重写getTasks方法。注意SchedulingPattern 的写法,这里给一个参考cronExpression表达式资料。

    public class MyTaskCollector implements TaskCollector { 
    
        public TaskTable getTasks() {
            SchedulingPattern pattern = new SchedulingPattern("* 0-23 * * *");
            Task task = new RedisTask(); 
            TaskTable ret = new TaskTable();
            ret.add(pattern, task); 
            
            return ret;
        }
    }

     完成了这些,最后来写我们自己的业务RedisTask()了,这里要注意的是调度,排除在上一次调度还没有完成的时候这次调度的时间又到了这种难过情况。

    public class RedisTask  extends Task {
    	
    	
    	public void execute(TaskExecutionContext executor) throws RuntimeException {
    		Scheduler scheduler = executor.getScheduler();
    		TaskExecutor[] executors = scheduler.getExecutingTasks();
    		if(executors!=null && executors.length>1)//调度
                    …………
                    …………
                    …………
            }
    }
    

     这是一种定时器比较老的写法,过两天更新一个定时器的零一中实现方法。 

  • 相关阅读:
    云? 云! 晕! 云计算适合创业公司么?
    批量转移Windows Server的DNS设置
    Signs that you are a bad programmer
    IsNull Function in PeopleSoft MetaSQL
    JS绘制曲线图
    Why does my shared clipboard not work?
    C#入门详解(2)
    C#入门详解(1)
    分享范玮琪最初的梦想
    像战士一样生活
  • 原文地址:https://www.cnblogs.com/ytliyang/p/5295638.html
Copyright © 2011-2022 走看看