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

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

  • 相关阅读:
    Android 程序员不得不收藏的个人博客(持续更新...)
    硬核讲解 Jetpack 之 LifeCycle 源码篇
    秉心说,不一样的 2019
    秉心说 2019 博文合集
    庖丁解牛 Activity 启动流程
    Jetpack Compse 实战 —— 全新的开发体验
    Box 黑科技 —— 支持手机端反编译 !
    “无处不在” 的系统核心服务 —— ActivityManagerService 启动流程解析
    如何正确的在 Android 上使用协程 ?
    【Medium 万赞好文】ViewModel 和 LIveData:模式 + 反模式
  • 原文地址:https://www.cnblogs.com/ytliyang/p/5295638.html
Copyright © 2011-2022 走看看