在web端写定时任务的方式

    xiaoxiao2021-03-25  121

    1、创建一个监听 实现 ServletContextListener类

    public class TimeTaskListener implements ServletContextListener{ private DayReportATask dayReportATask = new DayReportATask();        /**      * 本方法的描述:      * 在所有的filter和servlet都destroyed后通知web应用的所有的ServletContextListeners[that“本店”即将打烊啦]      */      public void contextDestroyed(ServletContextEvent sce) {          System.out.println("contextDestroyed…………");          dayReportATask.taskEnd();      }        /**      * 这个方法的描述:      * 在所有的filter和servlet初始化之前,所有的ServletContextListeners会收到[您所在的web应用的初始化工作开始啦]通知      */      public void contextInitialized(ServletContextEvent arg0) {          System.out.println("contextInitialized……");          dayReportATask.taskBegin();      }   }

    2、创建一个类执行定时任务 此处使用的是在特点时间点进行定时任务的启动,并周期为1天

    public class DayReportATask { // newScheduledThreadPool(int corePoolSize),corePoolSize是线程池的大小,       //即保持活动或者闲置的线程,它们是任务调度时用于并发执行的线程       private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);       ScheduledFuture<?> taskHandle;            /**       * 启动任务       */       public void taskBegin() {           // 定义一个任务           final Runnable task = new Runnable() {               public void run() {                   System.out.println("执行任务");               }           };              // scheduleAtFixedRate(Runnable command, long initialDelay, long period,           // TimeUnit unit):           // 通过ScheduledExecutorService的scheduleAtFixedRate来执行任务           // 参数           // command - 要执行的任务           // initialDelay - 首次执行的延迟时间           // period - 连续执行之间的周期           // unit - initialDelay 和 period 参数的时间单位           System.out.println("任务启动………………………………");           long oneDay = 24 * 60 * 60 * 1000;           long initDelay  = getTimeMillis("03:00:00") - System.currentTimeMillis();           initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;           taskHandle = scheduler.scheduleAtFixedRate(task, 1, 1, TimeUnit.SECONDS);   //        taskHandle = scheduler.scheduleAtFixedRate(task, initDelay, oneDay, TimeUnit.MILLISECONDS);       }          /**       * 结束任务       */       public void taskEnd() {           scheduler.shutdown();   //启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如果已经关闭,则调用没有其他作用。   //      List<Runnable> shutdownNow()试图停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。        }            /**       * 获取指定时间对应的毫秒数       * @param time "HH:mm:ss"       * @return       */       private static long getTimeMillis(String time) {           try {               DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");               DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");               Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);               return curDate.getTime();           } catch (ParseException e) {               e.printStackTrace();           }           return 0;       }   }

    3、在web.xml中配置监听

      <listener>       <listener-class>listeners.TimeTaskListener</listener-class>     </listener>  

    转载请注明原文地址: https://ju.6miu.com/read-8978.html

    最新回复(0)