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
- package org.quartz.examples.example4;
- import java.util.Date;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.quartz.JobDetail;
- import org.quartz.Scheduler;
- import org.quartz.SchedulerFactory;
- import org.quartz.SchedulerMetaData;
- import org.quartz.SimpleTrigger;
- import org.quartz.TriggerUtils;
- import org.quartz.impl.StdSchedulerFactory;
- /**
- * This Example will demonstrate how job parameters can be
- * passed into jobs and how state can be maintained
- *
- * @author Bill Kratzer
- */
- public class JobStateExample {
- public void run() throws Exception {
- Log log = LogFactory.getLog(JobStateExample.class);
- log.info("------- Initializing -------------------");
- // First we must get a reference to a scheduler
- SchedulerFactory sf = new StdSchedulerFactory();
- Scheduler sched = sf.getScheduler();
- log.info("------- Initialization Complete --------");
- log.info("------- Scheduling Jobs ----------------");
- // get a "nice round" time a few seconds in the future....
- long ts = TriggerUtils.getNextGivenSecondDate(null, 10).getTime();
- // job1 will only run 5 times, every 10 seconds
- JobDetail job1 = new JobDetail("job1", "group1", ColorJob.class);
- SimpleTrigger trigger1 = new SimpleTrigger("trigger1", "group1", "job1", "group1",
- new Date(ts), null, 4, 10000);
- // pass initialization parameters into the job
- job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
- job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
- // schedule the job to run
- Date scheduleTime1 = sched.scheduleJob(job1, trigger1);
- log.info(job1.getFullName() +
- " will run at: " + scheduleTime1 +
- " and repeat: " + trigger1.getRepeatCount() +
- " times, every " + trigger1.getRepeatInterval() / 1000 + " seconds");
- // job2 will also run 5 times, every 10 seconds
- JobDetail job2 = new JobDetail("job2", "group1", ColorJob.class);
- SimpleTrigger trigger2 = new SimpleTrigger("trigger2", "group1", "job2", "group1",
- new Date(ts + 1000), null, 4, 10000);
- // pass initialization parameters into the job
- // this job has a different favorite color!
- job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");
- job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
- // schedule the job to run
- Date scheduleTime2 = sched.scheduleJob(job2, trigger2);
- log.info(job2.getFullName() +
- " will run at: " + scheduleTime2 +
- " and repeat: " + trigger2.getRepeatCount() +
- " times, every " + trigger2.getRepeatInterval() / 1000 + " seconds");
- log.info("------- Starting Scheduler ----------------");
- // All of the jobs have been added to the scheduler, but none of the jobs
- // will run until the scheduler has been started
- sched.start();
- log.info("------- Started Scheduler -----------------");
- log.info("------- Waiting 60 seconds... -------------");
- try {
- // wait five minutes to show jobs
- Thread.sleep(60L * 1000L);
- // executing...
- } catch (Exception e) {
- }
- log.info("------- Shutting Down ---------------------");
- sched.shutdown(true);
- log.info("------- Shutdown Complete -----------------");
- SchedulerMetaData metaData = sched.getMetaData();
- log.info("Executed " + metaData.numJobsExecuted() + " jobs.");
- }
- public static void main(String[] args) throws Exception {
- JobStateExample example = new JobStateExample();
- example.run();
- }
- }