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)//调度
                    …………
                    …………
                    …………
            }
    }
    

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

  • 相关阅读:
    SpringBoot整合jsp
    SpringBoot常用application.properties配置
    SpringBoot入门
    vue cli创建vue项目
    vue 指令
    vue hello
    pytest doc
    atom
    java csvutil
    Django uuidfield 实现自动生成唯一列,并设置为主键
  • 原文地址:https://www.cnblogs.com/ytliyang/p/5295638.html
Copyright © 2011-2022 走看看