Java监听器,定时器

1、什么是监听器?

        所谓的监听器就好像JS中所学的事件,以及Java程序贪食蛇中根据获取的键盘上不同的键值,来点击的时候改变蛇运动的方 向。

2、监听器是怎么实现的?

        了解这个之前,首先要了解一个小知识就是,源:监听的是谁;动作:触发条件;响应:当这个条件满足的时候会执行的函数。

       

3、具体代码如下(只是实现了其中的某些接口):

package listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener()
public class MyListener implements ServletContextAttributeListener,HttpSessionAttributeListener {


    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("属性被添加了");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("属性被移除了");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("属性被替换了");
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("属性被添加了");
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("属性被移除了");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("属性被替换了");
    }
}

补充:ServletContext对象:生命周期 随着项目的启动而创建,随着项目的关闭而销毁。

4、什么是定时器?

        比如说,我们想要让我所写的一篇文章在在某个时刻向 一些地方进行推送,那么这个时候,我就需要用定时器

设置一个时间,在经过一段时间后就进行推送。

5、具体代码实现:

     1、Timer 

package listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ListenerDemo implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,14);//控制时
        calendar.set(Calendar.MINUTE,48);//控制分
        calendar.set(Calendar.SECOND,14);//控制秒
        Date date = calendar.getTime();//得出执行任务的时间
                /*定时器*/
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("1+1=2");
            }
        },date,1000*10);
             System.out.println("ServletContext创建了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("ServletContext销毁了");
    }
}

2、quartz

  1. package org.quartz.examples.example4;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.apache.commons.logging.Log;  
  6. import org.apache.commons.logging.LogFactory;  
  7. import org.quartz.JobDetail;  
  8. import org.quartz.Scheduler;  
  9. import org.quartz.SchedulerFactory;  
  10. import org.quartz.SchedulerMetaData;  
  11. import org.quartz.SimpleTrigger;  
  12. import org.quartz.TriggerUtils;  
  13. import org.quartz.impl.StdSchedulerFactory;  
  14.   
  15. /** 
  16.  * This Example will demonstrate how job parameters can be  
  17.  * passed into jobs and how state can be maintained 
  18.  *  
  19.  * @author Bill Kratzer 
  20.  */  
  21. public class JobStateExample {  
  22.   
  23.     public void run() throws Exception {  
  24.         Log log = LogFactory.getLog(JobStateExample.class);  
  25.   
  26.         log.info("------- Initializing -------------------");  
  27.   
  28.         // First we must get a reference to a scheduler  
  29.         SchedulerFactory sf = new StdSchedulerFactory();  
  30.         Scheduler sched = sf.getScheduler();  
  31.   
  32.         log.info("------- Initialization Complete --------");  
  33.   
  34.         log.info("------- Scheduling Jobs ----------------");  
  35.   
  36.         // get a "nice round" time a few seconds in the future....  
  37.         long ts = TriggerUtils.getNextGivenSecondDate(null10).getTime();  
  38.   
  39.         // job1 will only run 5 times, every 10 seconds  
  40.         JobDetail job1 = new JobDetail("job1""group1", ColorJob.class);  
  41.         SimpleTrigger trigger1 = new SimpleTrigger("trigger1""group1""job1""group1",  
  42.                 new Date(ts), null410000);  
  43.         // pass initialization parameters into the job  
  44.         job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");  
  45.         job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);  
  46.           
  47.         // schedule the job to run  
  48.         Date scheduleTime1 = sched.scheduleJob(job1, trigger1);  
  49.         log.info(job1.getFullName() +  
  50.                 " will run at: " + scheduleTime1 +    
  51.                 " and repeat: " + trigger1.getRepeatCount() +   
  52.                 " times, every " + trigger1.getRepeatInterval() / 1000 + " seconds");  
  53.   
  54.         // job2 will also run 5 times, every 10 seconds  
  55.         JobDetail job2 = new JobDetail("job2""group1", ColorJob.class);  
  56.         SimpleTrigger trigger2 = new SimpleTrigger("trigger2""group1""job2""group1",  
  57.                 new Date(ts + 1000), null410000);  
  58.         // pass initialization parameters into the job  
  59.         // this job has a different favorite color!  
  60.         job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");  
  61.         job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);  
  62.           
  63.         // schedule the job to run  
  64.         Date scheduleTime2 = sched.scheduleJob(job2, trigger2);  
  65.         log.info(job2.getFullName() +  
  66.                 " will run at: " + scheduleTime2 +  
  67.                 " and repeat: " + trigger2.getRepeatCount() +  
  68.                 " times, every " + trigger2.getRepeatInterval() / 1000 + " seconds");   
  69.   
  70.   
  71.         log.info("------- Starting Scheduler ----------------");  
  72.   
  73.         // All of the jobs have been added to the scheduler, but none of the jobs  
  74.         // will run until the scheduler has been started  
  75.         sched.start();  
  76.   
  77.         log.info("------- Started Scheduler -----------------");  
  78.           
  79.         log.info("------- Waiting 60 seconds... -------------");  
  80.         try {  
  81.             // wait five minutes to show jobs  
  82.             Thread.sleep(60L * 1000L);   
  83.             // executing...  
  84.         } catch (Exception e) {  
  85.         }  
  86.   
  87.         log.info("------- Shutting Down ---------------------");  
  88.   
  89.         sched.shutdown(true);  
  90.   
  91.         log.info("------- Shutdown Complete -----------------");  
  92.   
  93.         SchedulerMetaData metaData = sched.getMetaData();  
  94.         log.info("Executed " + metaData.numJobsExecuted() + " jobs.");  
  95.   
  96.     }  
  97.   
  98.     public static void main(String[] args) throws Exception {  
  99.   
  100.         JobStateExample example = new JobStateExample();  
  101.         example.run();  
  102.     }  
  103.   
  104. }  






猜你喜欢

转载自blog.csdn.net/weixin_42047611/article/details/80697756
今日推荐