java定时器

合集下载

java 根据时间段记录计算时长的方法

java 根据时间段记录计算时长的方法

【java 根据时间段记录计算时长的方法】一、时间的重要性时间是一种珍贵的资源,在生活和工作中都扮演着重要的角色。

在编程中,对时间的使用也是必不可少的,特别是在需要记录和计算时间长度的场景下。

而在Java中,如何根据时间段记录并计算时长,是一个常见且重要的问题。

在本文中,我将探讨这个主题,并提供一些解决方案和建议。

二、通过时间戳记录时间段1. 时间戳的概念在Java中,时间戳是一种以毫秒为单位的表示时间的方式,可以通过System.currentTimeMillis()方法获取当前时间的时间戳。

时间戳可以精确地表示一个时间点,也可以用来计算时间长度。

2. 记录时间段的开始和结束时间戳要记录一个时间段的时长,首先需要获取开始和结束时间点的时间戳。

在实际应用中,可以使用System.currentTimeMillis()方法来获取当前时间戳,并将其保存下来作为开始时间戳;同样地,当时间段结束时也需要获取一个结束时间戳。

3. 计算时长有了开始时间戳和结束时间戳后,就可以很容易地计算出时间段的时长。

通过简单地相减操作,即可得到时间段的时长,然后可以将其转换成所需的时间单位,如秒、分钟或小时。

三、使用Java 8的Time API记录时间段1. Java 8的Time APIJava 8引入了新的时间日期API,位于java.time包下,提供了更加灵活、方便的时间处理方式。

在使用Java 8的Time API记录时间段时,可以使用LocalDateTime类来表示时间点,Duration类来表示时长。

2. 记录时间段的开始和结束时间点使用LocalDateTime类可以轻松地表示时间段的开始和结束时间点,同时Duration类可以计算时间段的时长。

可以通过LocalDateTime.now()获取当前时间点,并将其保存下来作为开始时间;在时间段结束时也需要获取一个结束时间。

3. 计算时长通过Duration.between()方法可以计算出时间段的时长,得到一个Duration对象,然后可以调用toMinutes()、toHours()等方法将时间段转换成所需的时间单位。

java 定时器用法

java 定时器用法

Java定时器用法详解一、简介Java定时器(Timer)是Java编程语言中用于实现定时任务的一种工具。

它允许开发者在指定的时间间隔内执行特定的代码块,从而实现定时操作。

本文将详细介绍Java定时器的用法,包括创建定时器、设置任务、启动和停止定时器等内容。

二、创建定时器在Java中,要使用定时器,首先需要导入`java.util.Timer`类。

创建定时器的方法如下:import java.util.Timer;public class MyTimer {public static void main(String[] args) {Timer timer = new Timer();}}三、设置任务定时器的核心功能是执行定时任务,因此需要为定时器设置一个任务。

在Java 中,可以通过创建一个继承自`java.util.TimerTask`的类来实现定时任务。

以下是一个简单的示例:import java.util.TimerTask;class MyTask extends TimerTask {@Overridepublic void run() {System.out.println("定时任务执行");}}四、启动定时器创建好定时器和任务后,接下来需要启动定时器。

可以使用`schedule()`方法来设置定时器的任务和执行间隔。

以下是一个完整的示例:import java.util.Timer;import java.util.TimerTask;class MyTask extends TimerTask {@Overridepublic void run() {System.out.println("定时任务执行");}}public class MyTimer {public static void main(String[] args) {Timer timer = new Timer();MyTask task = new MyTask();timer.schedule(task, 0, 1000); // 立即执行,然后每隔1秒执行一次}}五、停止定时器在某些情况下,可能需要停止定时器的执行。

JAVA随笔篇一(Timer源代码分析和scheduleAtFixedRate的使用)

JAVA随笔篇一(Timer源代码分析和scheduleAtFixedRate的使用)

JAVA随笔篇⼀(Timer源代码分析和scheduleAtFixedRate的使⽤)写完了基础篇,想了⾮常久要不要去写进阶篇。

去写JSP等等的⽤法。

最后决定先不去写。

由于⾃⼰并⾮JAVA⽅⾯的⼤⽜。

眼下也在边做边学,所以决定先将⾃⼰不懂的拿出来学并记下来。

Timer是Java⾃带的java.util.Timer类,通过调度⼀个java.util.TimerTask任务。

这样的⽅式能够让程序依照某⼀个频度运⾏。

1、Timer类的源代码分析:public class Timer {/*** The timer task queue. This data structure is shared with the timer* thread. The timer produces tasks, via its various schedule calls,* and the timer thread consumes, executing timer tasks as appropriate,* and removing them from the queue when they're obsolete.*/private TaskQueue queue = new TaskQueue();/*** The timer thread.*/private TimerThread thread = new TimerThread(queue);⾸先Timer类定义了两个私有变量TaskQueue和TimerThread。

TaskQueue:Timer类定义了⼀个定时器任务队列。

⼀个TimerTasks的优先级队列。

class TaskQueue {/*** Priority queue represented as a balanced binary heap: the two children* of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is* ordered on the nextExecutionTime field: The TimerTask with the lowest* nextExecutionTime is in queue[1] (assuming the queue is nonempty). For* each node n in the heap, and each descendant of n, d,* n.nextExecutionTime <= d.nextExecutionTime.*/private TimerTask[] queue = new TimerTask[128];TimerThread:Timer类的任务运⾏线程。

java计时器用法介绍

java计时器用法介绍

java计时器用法简介所有类型的Java 应用程序一般都需要计划重复执行的任务。

企业应用程序需要计划每日的日志或者晚间批处理过程。

一个J2SE 或者J2ME 日历应用程序需要根据用户的约定计划闹铃时间。

不过,标准的调度类Timer 和TimerTask 没有足够的灵活性,无法支持通常需要的计划任务类型。

在本文中,Java 开发人员Tom White 向您展示了如何构建一个简单通用的计划框架,以用于执行任意复杂的计划任务。

我将把java.util.Timer 和java.util.TimerTask 统称为Java 计时器框架,它们使程序员可以很容易地计划简单的任务(注意这些类也可用于J2ME 中)。

在Java 2 SDK, Standard Edition, Version 1.3 中引入这个框架之前,开发人员必须编写自己的调度程序,这需要花费很大精力来处理线程和复杂的Object.wait() 方法。

不过,Java 计时器框架没有足够的能力来满足许多应用程序的计划要求。

甚至一项需要在每天同一时间重复执行的任务,也不能直接使用Timer 来计划,因为在夏令时开始和结束时会出现时间跳跃。

本文展示了一个通用的Timer 和TimerTask 计划框架,从而允许更灵活的计划任务。

这个框架非常简单——它包括两个类和一个接口——并且容易掌握。

如果您习惯于使用Java 定时器框架,那么您应该可以很快地掌握这个计划框架。

计划单次任务计划框架建立在Java 定时器框架类的基础之上。

因此,在解释如何使用计划框架以及如何实现它之前,我们将首先看看如何用这些类进行计划。

想像一个煮蛋计时器,在数分钟之后(这时蛋煮好了)它会发出声音提醒您。

清单 1 中的代码构成了一个简单的煮蛋计时器的基本结构,它用Java 语言编写:清单1. EggTimer 类EggTimer 实例拥有一个Timer 实例,用于提供必要的计划。

用start() 方法启动煮蛋计时器后,它就计划了一个TimerTask,在指定的分钟数之后执行。

JAVA:定时器的三种方法(详细注解)

JAVA:定时器的三种方法(详细注解)

JAVA:定时器的三种⽅法(详细注解)在Java中为我们提供了Timer来实现定时任务,当然现在还有很多定时任务框架,⽐如说Spring、QuartZ、Linux Cron等等,⽽且性能也更加优越。

但是我们想要深⼊的学习就必须先从最简单的开始。

第⼀种:创建⼀个thread,然后让它在while循环⾥⼀直运⾏着,通过sleep⽅法来达到定时任务的效果,代码如下public class Task1 {public static void main(String[] args) {// run in a second// 每⼀秒钟执⾏⼀次final long timeInterval = 1000;Runnable runnable = new Runnable() {public void run() {while (true) {// ------- code for task to run// ------- 要运⾏的任务代码System.out.println("Hello, stranger");// ------- ends heretry {// sleep():同步延迟数据,并且会阻塞线程Thread.sleep(timeInterval);} catch (InterruptedException e) {e.printStackTrace();}}}};//创建定时器Thread thread = new Thread(runnable);//开始执⾏thread.start();}}第⼆种:启动和去取消任务时可以控制,可以指定你想要的delay(开始执⾏的等待时间)时间,在实现时,Timer类可以调度任务,TimerTask 则是通过在run()⽅法⾥实现具体任务。

Timer实例可以调度多任务,它是线程安全的。

当Timer的构造器被调⽤时,它创建了⼀个线程,这个线程可以⽤来调度任务。

java定时器线程池(ScheduledThreadPoolExecutor)的实现

java定时器线程池(ScheduledThreadPoolExecutor)的实现

java定时器线程池(ScheduledThreadPoolExecutor)的实现前⾔定时器线程池提供了定时执⾏任务的能⼒,即可以延迟执⾏,可以周期性执⾏。

但定时器线程池也还是线程池,最底层实现还是ThreadPoolExecutor,可以参考我的另外⼀篇⽂章多线程–精通ThreadPoolExecutor。

特点说明1.构造函数public ScheduledThreadPoolExecutor(int corePoolSize) {// 对于其他⼏个参数在ThreadPoolExecutor中都已经详细分析过了,所以这⾥,将不再展开// 这⾥我们可以看到调⽤基类中的⽅法时有个特殊的⼊参DelayedWorkQueue。

// 同时我们也可以发现这⾥并没有设置延迟时间、周期等参数⼊⼝。

// 所以定时执⾏的实现必然在DelayedWorkQueue这个对象中了。

super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue());}2.DelayedWorkQueueDelayedWorkQueue是在ScheduledThreadPoolExecutor的⼀个内部类,实现了BlockingQueue接⼝⾥⾯存放任务队列的数组如下:private RunnableScheduledFuture<?>[] queue =new RunnableScheduledFuture<?>[INITIAL_CAPACITY];我们分析过ThreadPoolExecutor,它从任务队列中获取任务的⽅式为poll和take两种,所以看⼀下poll和take两个⽅法的源码,回顾⼀下,ThreadPoolExecutor它会调⽤poll或take⽅法,先poll,再take,只要其中⼀个接⼝有返回就⾏public RunnableScheduledFuture<?> poll() {final ReentrantLock lock = this.lock;lock.lock();try {RunnableScheduledFuture<?> first = queue[0];// 这⾥有个getDelay,这是关键点,获取执⾏延时时间// 但是如果我们有延时设置的话,这就返回空了,然后就会调⽤take⽅法if (first == null || first.getDelay(NANOSECONDS) > 0)return null;elsereturn finishPoll(first);} finally {lock.unlock();}}public RunnableScheduledFuture<?> take() throws InterruptedException {final ReentrantLock lock = this.lock;lock.lockInterruptibly();try {for (;;) {RunnableScheduledFuture<?> first = queue[0];if (first == null)available.await();else {// 获取延时时间long delay = first.getDelay(NANOSECONDS);if (delay <= 0)return finishPoll(first);first = null; // don't retain ref while waitingif (leader != null)available.await();else {Thread thisThread = Thread.currentThread();leader = thisThread;try {// 使⽤锁,执⾏延时等待。

javaTimer定时每天凌晨1点执行任务

javaTimer定时每天凌晨1点执行任务

javaTimer定时每天凌晨1点执⾏任务下⾯给⼤家介绍java Timer 定时每天凌晨1点执⾏任务,具体代码如下所⽰:import java.util.TimerTask;/*** 执⾏内容* @author admin_Hzw**/public class Task extends TimerTask {public void run() {System.out.println("我有⼀头⼩⽑驴!");}}import java.util.Calendar;import java.util.Date;import java.util.Timer;/*** 任务管理* @author admin_Hzw**/public class TimerManager {/*** @param args*/public static void main(String[] args) {new TimerManager();}//时间间隔(⼀天)private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;public TimerManager() {Calendar calendar = Calendar.getInstance();calendar.set(Calendar.HOUR_OF_DAY, 1); //凌晨1点calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);Date date=calendar.getTime(); //第⼀次执⾏定时任务的时间//如果第⼀次执⾏定时任务的时间⼩于当前的时间//此时要在第⼀次执⾏定时任务的时间加⼀天,以便此任务在下个时间点执⾏。

如果不加⼀天,任务会⽴即执⾏。

if (date.before(new Date())) {date = this.addDay(date, 1);}Timer timer = new Timer();Task task = new Task();//安排指定的任务在指定的时间开始进⾏重复的固定延迟执⾏。

JAVA定时器的三种方法(详细注解)

JAVA定时器的三种方法(详细注解)

JAVA定时器的三种方法(详细注解)在Java中,有三种主要的定时器方法可以实现任务的定时执行。

这些方法包括Timer类、ScheduledThreadPoolExecutor类和TimerTask类。

下面将详细介绍这三种定时器方法的使用。

1. Timer类:Timer类是Java提供的一个基本的定时器类,可以用于在指定的时间间隔内执行指定的任务。

Timer类提供了schedule(和scheduleAtFixedRate(两个方法,用于按照指定的时间间隔执行任务。

(1)schedule(方法:该方法用于在指定的时间间隔后执行任务。

它的语法如下:public void schedule(TimerTask task, long delay)参数task表示要执行的任务,它是一个实现了TimerTask接口的类的实例。

参数delay表示延迟的时间,以毫秒为单位。

例如,下面的代码使用Timer类的schedule(方法,在延迟2秒后执行一个任务:```public void ruSystem.out.println("任务执行了");}},2000);```当运行上述代码后,程序将会输出"任务执行了"。

(2)scheduleAtFixedRate(方法:该方法用于以固定的时间间隔执行任务。

它的语法如下:public void scheduleAtFixedRate(TimerTask task, long delay, long period)参数task表示要执行的任务,它是一个实现了TimerTask接口的类的实例。

参数delay表示延迟的时间,以毫秒为单位。

参数period表示每次任务执行间隔的时间,也是以毫秒为单位。

例如,下面的代码使用Timer类的scheduleAtFixedRate(方法,延迟2秒后开始执行一个任务,并且每隔1秒执行一次:```public void ruSystem.out.println("任务执行了");}},2000,1000);```当运行上述代码后,程序将会输出"任务执行了",并且每隔1秒输出一次。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

util包中的定时器学习相对比较简单,学习java定时器主要要熟悉两个类,Timer类和TimerTask类。

定时器类Timer在java.util包中。

使用时,先实例化,然后使用实例的schedule(TimerTask task, long delay)方法,设定指定的任务task在指定的延迟delay后执行。

定时器任务类TimerTask 是抽象类,继承并重写其run()方法,可实现具体任务。

schedule(TimerTask task, Date time)设定指定任务task在指定时间time执行。

cancel()方法结束这个定时器。

schedule(TimerTask task, long delay, long period)方法设定指定任务task在指定延迟delay后进行固定延迟peroid的执行。

scheduleAtFixedRate(TimerTask task, long delay, long period)方法设定指定任务task在指定延迟delay后进行固定频率peroid的执行。

要实现一个定时任务,运用java中的Timer和TimerTask类可以非常容易实现实时调用处理函数。

这两个类使用起来非常方便,可以完成我们对定时器的绝大多数需要。

package com.csdn.heima;import java.io.IOException;import java.util.Scanner;import java.util.Timer;public class TimerTest {public static void main(String[] args){Timer timer = new Timer();timer.schedule(new MyTask(), 1000, 3000);//在1秒后执行此任务,以后每隔1秒执行这个MyTask任务.while(true){Scanner scan = new Scanner(System.in);String str = scan.nextLine();if(str.equals("ok")){timer.cancel();// 终止此计时器,丢弃所有当前已安排的任务。

}}}static class MyTask extends java.util.TimerTask{public void run() {System.out.println("------itcast-----------间隔3秒打印一次!----------csdn-------------");}}}JA V A WEB定时器,定时器的启动一般随web server的启动而启动,一般有两种方法.方法一:在web.xml里配置一个Servlet,继承HttpServlet,并设置其随web server的启动而启动。

然后在该Servlet的init()方法里启动定时器,在destory()方法里销毁定时器。

方法二:在web.xml里配置一个Listener,继承ServletContextListener,然后在该Listener的初始化方法里启动定时器,在其销毁的方法朝左销毁定时器。

在servlet中启动定时器一,继承HttpServlet的写法:1,Servlet1importjava.io.IOException;2importjava.util.Timer;3importjavax.servlet.RequestDispatcher;4importjavax.servlet.ServletContext;5importjavax.servlet.ServletException;6importjavax.servlet.http.HttpServlet;7importjavax.servlet.http.HttpServletRequest;8importjavax.servlet.http.HttpServletResponse;91011publicclassConvergeDataServlet extends HttpServlet {1213private static final long serialVersionUID = 1L;1415private Timer timer1 = null;1617private Task task1;1819/**20* Constructor of the object.21*/22public ConvergeDataServlet() {23super();24}2526/**27* Destruction of the servlet.28*/29public void destroy() {30super.destroy();31if(timer1!=null){32timer1.cancel();33}34}353637public void doGet(HttpServletRequest request, HttpServletResponse response) 38throws ServletException, IOException {3940}414243public void doPost(HttpServletRequest request, HttpServletResponse response) 44throws ServletException, IOException {45doGet(request, response);46}4748// init方法启动定时器49public void init() throws ServletException {5051ServletContext context = getServletContext();5253// (true为用定时间刷新缓存)54String startTask = getInitParameter("startTask");5556// 定时刷新时间(分钟)57Long delay = Long.parseLong(getInitParameter("delay"));5859// 启动定时器60if(startTask.equals("true")){61timer1 = new Timer(true);62task1 = new Task(context);63timer1.schedule(task1, delay * 60 * 1000, delay * 60 * 1000);64}65}66}2,任务67import java.util.TimerTask;6869import javax.servlet.ServletContext;7071public class Task extends TimerTask{7273private ServletContext context;7475private static boolean isRunning = true;7677public Task(ServletContext context){78this.context = context;79}808182@Override83public void run() {84if(isRunning){8586}87}8889}3,web.xml中的配置< servlet >< servlet-name >taskservlet< / servlet-name >< servlet-class >com.task< /servlet-class >< init-param >< param-name >startTask< /param-name >< param-value >true< /param-value >< /init-param >< init-param >< param-name >intervalTime< /param-name >< param-value >1< /param-value >< /init-param >< load-on-startup >300< /load-on-startup >< /servlet >二,继承ServletContextListener1,定时器/****/package com.annlee.website.util;import java.util.Timer;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;/*** @author Administrator 定时器*/public class TimerListener implements ServletContextListener {private Timer timer;private AnnleeTimerTask task;public void contextDestroyed(ServletContextEvent arg0) {timer.cancel();System.out.println("定时器已销毁");}public void contextInitialized(ServletContextEvent event) {timer = new java.util.Timer(true);task = new AnnleeTimerTask(event.getServletContext());System.out.println("定时器已启动");timer.schedule(task, 0, 60 * 1000);System.out.println("已经添加任务调度表");}}2,任务package com.annlee.website.util;import java.util.Calendar;import java.util.TimerTask;import javax.servlet.ServletContext;import mAccessDataService;/*** 定时器的任务*/public class AnnleeTimerTask extends TimerTask {private ServletContext context;private static boolean isRunning = false;private static boolean flag = true;private static final int C_SCHEDULE_HOUR = 0;private UsmAccessDataService accessDataService;public AnnleeTimerTask(ServletContext context){this.context = context;}public void run() {accessDataService = new UsmAccessDataService();Calendar cal = Calendar.getInstance();if (!isRunning) {if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY) && flag) { isRunning = true;// accessDataService.SendHttpByMonth(0,0, 0);System.out.println("正在执行任务");isRunning = false;flag = false;context.log("指定任务执行结束");}} else {context.log("上一次任务执行还未结束");}if(C_SCHEDULE_HOUR != cal.get(Calendar.HOUR_OF_DAY)){flag = true;}}}3,web.xml中的配置<listener><listener-class>com.annlee.website.util.TimerListener</listener-class></listener>====================================================================== =其实我想实现的就是在每天23:59:59 这个时间调用1次方法就结束每天如此希望高手指点我来帮他解答2011-8-19 16:58满意回答import java.util.GregorianCalendar;import java.util.Timer;import java.util.TimerT ask;/**** @author Administrator*/public class TimerDemo {public static void main(String[] args) {/** 对象句柄*/final TimerDemo td = new TimerDemo();// Java的计时器,可以规定从某一个时刻起,以后每对少时间循环执行一次new Timer().schedule(new TimerTask() {@Overridepublic void run() {td.print();}}, new GregorianCalendar(2011, 8, 19, 23, 59, 59).getTime(),24 * 60 * 60 * 1000);}/*** 要调用的函数*/private void print() {System.out.println("Test");}}====================================================================== =========下面是我写的程序,就是用2个定时器中断T0和T1每隔一秒钟1S钟让数码管的数字减1,同时流水灯流一下。

相关文档
最新文档