




已阅读5页,还剩8页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
java Timer定时器实例 Spring实例2009-09-11 14:48package com.loong.mail.timer;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class TimerListen implements ServletContextListener private Timer timer = null; public void contextDestroyed(ServletContextEvent arg0) timer.cancel(); public void contextInitialized(ServletContextEvent arg0) try SimpleDateFormat fTime = new SimpleDateFormat(yyyy/MM/dd HH:mm:ss); SimpleDateFormat fTime_1=new SimpleDateFormat(yyyy/MM/dd); Date d1 = fTime.parse(fTime_1.format(new Date()+ 14:17:00); timer = new Timer(true); /设置任务计划,启动和间隔时间 / System.out.print(rundate); /timer.scheduleAtFixedRate(new MailTimerTask(arg0.getServletContext().getRealPath(/),rundate,1000*60*60*24); timer.scheduleAtFixedRate(new MailTimerTask(arg0.getServletContext().getRealPath(/),d1, 24*60*60*1000); catch (Exception e) System.out.print(e.getMessage(); package com.loong.mail.timer;import java.util.Date;import java.util.TimerTask;import com.loong.filter.CFile;import com.loong.mail.sendmail.SendMail;import com.loong.user.service.UserService;import java.io.*;import .*;import java.io.InputStream;public class MailTimerTask extends TimerTaskprivate String path;public MailTimerTask(String path) this.path=path; System.out.println(test+new Date(); run();public void run() System.out.println(new Date(); SendMail sm = new SendMail(); sm.SystemMail(, wmq534, ); /UserService us = new UserService(); /us.getUserInfo(userId); /查找数据库中当天消费金额大于20的用户的用户名,email,消费金额、/使用freemarker生成html文件。传递到sendMails,发送到邮箱 / BufferedReader in=null; /StringBuffer sb=new StringBuffer(); /try /URL url=new URL(/html/paihang.jsp); /HttpURLConnection conn = (HttpURLConnection)url.openConnection(); /conn.setRequestProperty(Accept-Language,zh-cn); / conn.setRequestProperty(user-agent,mozilla/4.0 (compatible; msie 6.0; windows 2000); / conn.setRequestMethod(POST); / conn.setUseCaches(false); /conn.connect(); /int code=conn.getResponseCode(); /InputStream l_urlStream=null; /if(code!=404) / l_urlStream =conn.getInputStream(); /else / l_urlStream=conn.getErrorStream(); / /in = new BufferedReader(new InputStreamReader(l_urlStream,UTF-8); /String inputLine=; /while (inputLine = in.readLine() != null) / / sb.append(inputLine); /sb.append(rn); /* HtmlPage html=new HtmlPage(); CFile.writeFile(path+/inc/phb.htm,html.html().toString(), null); */ /conn.disconnect();/ catch(MalformedURLException e)/ CFile.writeFile(path+/inc/phb1.htm,URL连接异常:+e.getMessage(), null);/ System.out.print(e.getMessage();/ catch(IOException e)/ CFile.writeFile(path+/inc/phb1.htm,IO异常:+e.getMessage(), null);/ System.out.print(e.getMessage();/ / finally/ try/ if(in!=null)/ in.close();/ catch(Exception e)/ / System.out.print(e.getMessage();/ / Spring 中的定时任务配置实例 SayHello 0/10 * * * * ? package test;import org.apache.log4j.*;public class TaskJob public static Logger log = Logger .getLogger(TaskJob.class); public void SayHello() / TODO Auto-generated method stub try (处理任务开始.); / 业务逻辑代码调用 System.out.println(时间 + new java.util.Date().toLocaleString() + -大家好啊!); (处理任务结束!); catch (Exception e) log.error(处理任务出现异常, e); java中定时器timer类的实现和源代码2007-11-01 08:59在Windows编程中可以调用SetTimer在指定窗口安装定时器(Timer),定时器可以在指定的时间间隔周期性回调用户指定的方法,用来执行周期性的任务,如果想取消定时器,可以调用KillTimer取消。但是在java标准包里中并没有这种类。下面介绍的这个类包可以实现上述功能。下面是接口,需要支持定时器功能的类要实现这个接口:TimerClient.java package com.ly.util;/* TimerClient Interface* version 1.0, 8 October 1995*/public interface TimerClient void timerEvent(int id);下面是定时器的实现,包括三个类:TimerCtl,TimerTask,TimerTasks。其中TimerTask用来描述定时器信息。TimerTasks是一个TimerTask的列表,这样我们就可以同时在一个应用中安插多个定时器。TimerCtl是定时器控制类,是个线程,不停地检查TimerTasks中是否有TimerTask到期,要是有TimerTask到达指定的时间,则回调TimerTask指定的TimerClient的timerEvent接口。TimerCtl.java package com.ly.util;import java.util.Vector;import java.util.Enumeration;/import com.borland.jb.util.Diagnostic;/* Timer Component* Note:* - The successful operation of this timer requires clients to execute simple, short* code snippets when called back by the engine. Otherwise the queues delivery* mechanism will be held up* Further work:* - When Thread.Interrupt is implemented we can switch from the busy wait model to* the calculated wait model. Without the interrupt the thread waits for the* calculated interval before waking up. This is a problem if another shorter* request arrives. For now well assume the minimum resolution of the timer is* 100ms.* version 1.0, 2 October 1995*/public class TimerCtl static TimerTasks timerTasks; public TimerCtl() /* * Start a timer running */ public static void startTimer(TimerClient client, int eventId, long delay, boolean repeat) / create the timer if necessary if (timerTasks = null) timerTasks = new TimerTasks(); timerTasks.start(); /Diagnostic.out.println(TIMER: startTimer+eventId); / add the new task to the queue timerTasks.add(client, eventId, delay, repeat); /* * Stop a timer */ public static void stopTimer(TimerClient client, int eventId) /Diagnostic.out.println(TIMER: stopTimer+eventId); if(timerTasks != null) timerTasks.end(client, eventId); class TimerTasks extends Thread Vector tasks = new Vector(); boolean suspended = false; boolean sleeping = false; /* * Thread task runner */ public void run() / Loop forever while (true) long sleepTime = 0; / Ensure that the tasks class is protected synchronized (tasks) /Diagnostic.out.println(TIMER: Tick); / Scan the job list for any jobs which may fire. / Mark one-shot jobs for deletion / Calculate the maximum time we can sleep for sleepTime = scan(); / Delete DeletePending jobs. DeletePending jobs result from one-shots which have / been sent, and repeat jobs which have been cancelled. Jobs may have been / cancelled during the Scan process. purge(); / Suspend timer if necessary if (tasks.size() = 0) /Diagnostic.out.println(TIMER: Suspend); try synchronized(this) suspended = true; wait(); catch (InterruptedException e) else /Diagnostic.out.println(TIMER: Suggested Sleeping for +sleepTime); if (sleepTime = 0) try sleeping = true; sleep(sleepTime); sleeping = false; catch (InterruptedException i) /Diagnostic.out.println(TIMER: Caught me napping); /* * Add a new task */ public void add(TimerClient client, int eventId, long delay, boolean repeat) TimerTask t = new TimerTask(client, eventId, delay, repeat); synchronized (tasks) tasks.addElement(Object)t); / Want instant response - wake the thread if its napping / unfortunately the interrupt() method is not working/ if (sleeping)/ interrupt(); if (suspended) synchronized(this) notify(); /Diagnostic.out.println(TIMER: Resume); suspended = false; /* * Find the job and mark it for deletion */ public void end(TimerClient client, int eventId) synchronized (tasks) for (int i = 0; i tasks.size(); i+) TimerTask t = (TimerTask)tasks.elementAt(i); /if (!t.deletePending & t.client = client & t.eventId = eventId) if (t.deletePending = false & t.client = client & t.eventId = eventId) / JPBS - if we dont reset repeat, deletePending will be set again t.repeat = false; t.deletePending = true; break; /* * Clear out all the dead wood */ void purge() for (int i = 0; i tasks.size(); i+) TimerTask t = (TimerTask)tasks.elementAt(i); if (t.deletePending) /Diagnostic.out.println(TIMER: purged); tasks.removeElementAt(i); i-; long scan() / The value added to the current time determines the MAX time until / the next scan / This is 100 now since errupt() is not implemented long nextTime = System.currentTimeMillis() +
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 江苏联合职业技术学院《税务会计学》2023-2024学年第二学期期末试卷
- 鲁东大学《药物化学导论》2023-2024学年第二学期期末试卷
- 重庆文理学院《操作系统B》2023-2024学年第二学期期末试卷
- 哈尔滨广厦学院《高等分离工程》2023-2024学年第二学期期末试卷
- 兰州资源环境职业技术大学《现代交换技术》2023-2024学年第二学期期末试卷
- 黄河水利职业技术学院《产品策划》2023-2024学年第二学期期末试卷
- 长垣烹饪职业技术学院《创业管理》2023-2024学年第二学期期末试卷
- 长春健康职业学院《移动应用开发实践》2023-2024学年第二学期期末试卷
- 中山火炬职业技术学院《生物化学与分子生物学实验》2023-2024学年第二学期期末试卷
- 南京工业职业技术大学《政治经济学原理》2023-2024学年第二学期期末试卷
- 延迟退休合同协议
- 消毒隔离知识培训课件
- 课后托管服务的岗位职责与管理
- 技术合作协议范本
- DB32-T 5082-2025 建筑工程消防施工质量验收标准
- 2025年度建筑施工安全演练计划
- 生产车间6S培训
- 托幼机构十项卫生保健制度
- 彩钢板围挡搭设施工方案
- 山东2025年山东省烟草专卖局(公司)高校毕业生招聘208人笔试历年参考题库附带答案详解
- 船舶工程设备租赁保障措施
评论
0/150
提交评论