The timing/planning function mainly uses the Timer object, which still uses multi-threading for processing internally, so it is still very closely related to thread technology.
The main function of the Timer class is to set up scheduled tasks, but the class that encapsulates the task is the TimerTask class. TimerTask class is an abstract class.
The execution time of the task is later than the current time-----The effect of execution in the future
import java.util.Date; import java.util.TimerTask; public class MyTask extends TimerTask{ @Override public void run() { System.out.println("任务执行了, 时间为:" + new Date()); } } public class Test1 { public static void main(String[] args){ System.out.println("当前时间为: " + new Date()); Calendar calendarRef = Calendar.getInstance(); calendarRef.add(Calendar.SECOND, 10); Date runDate = calendarRef.getTime(); MyTask task = new MyTask(); // 查看Timer构造方法,创建一个Timer就是启动一个新的线程 Timer timer = new Timer(); timer.schedule(task, runDate); // 定时器在某个时间(runDate)执行某个任务(task) } }
Free online learning video sharing: java video
Timer allows multiple TimerTask tasks and delayed tests
TimerTask is executed sequentially one by one in a queue, so the execution time is It may not be consistent with the expected time, because the previous task may take a long time, and the running time of the subsequent task will also be delayed.
import java.util.Date; import java.util.TimerTask; public class MyTaskA extends TimerTask{ @Override public void run() { try { System.out.println("A begin timer, 时间为:" + new Date()); Thread.sleep(20000); System.out.println("A end timer, 时间为:" + new Date()); } catch (InterruptedException e) { e.printStackTrace(); } } } import java.util.Date; import java.util.TimerTask; public class MyTaskB extends TimerTask{ @Override public void run() { System.out.println("B begin timer, 时间为:" + new Date()); System.out.println("B end timer, 时间为:" + new Date()); } } import java.util.Calendar; import java.util.Date; import java.util.Timer; public class Test1 { public static void main(String[] args){ System.out.println("当前时间为: " + new Date()); Calendar calendarRef1 = Calendar.getInstance(); Date runDate1 = calendarRef1.getTime(); System.out.println("A计划时间为: " + runDate1); Calendar calendarRef2 = Calendar.getInstance(); calendarRef2.add(Calendar.SECOND, 10); Date runDate2 = calendarRef2.getTime(); System.out.println("B计划时间为: " + runDate2); MyTaskA task1 = new MyTaskA(); MyTaskB task2 = new MyTaskB(); Timer timer = new Timer(); timer.schedule(task1, runDate1); // 定时器在某个时间(runDate)执行某个任务(task) timer.schedule(task2, runDate2); } }
schedule(TimerTask task, Date firstTime, long period)
The function of this method is to execute in an infinite loop at the specified interval after the specified date a certain task.
import java.util.Date; import java.util.TimerTask; public class MyTask extends TimerTask{ @Override public void run() { System.out.println("任务开始: "+new Date()); System.out.println("mytask..."); System.out.println("任务结束: "+new Date()); } } import java.util.Calendar; import java.util.Date; import java.util.Timer; public class Run { public static void main(String[] args){ System.out.println("当前时间为:"+new Date()); Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, 10); Date runDate1 = c.getTime(); System.out.println("计划时间为:"+runDate1); MyTask myTask = new MyTask(); Timer timer = new Timer(); timer.schedule(myTask, runDate1, 10000); } }
The cancel() method of the TimerTask class
The function of the cancel() method in the TimerTask class is to clear itself from the task queue.
import java.util.Date; import java.util.TimerTask; public class MyTaskA extends TimerTask{ @Override public void run() { System.out.println("A run timer="+new Date()); this.cancel(); System.out.println("A任务自己移除自己"); } } import java.util.Date; import java.util.TimerTask; public class MyTaskB extends TimerTask{ @Override public void run() { System.out.println("B run timer="+new Date()); } } import java.util.Calendar; import java.util.Date; import java.util.Timer; public class Run { public static void main(String[] args){ System.out.println("当前时间为:"+new Date()); Calendar c = Calendar.getInstance(); Date runDate1 = c.getTime(); System.out.println("计划时间为:"+runDate1); MyTaskA myTaskA = new MyTaskA(); MyTaskB myTaskB = new MyTaskB(); Timer timer = new Timer(); timer.schedule(myTaskA, runDate1, 4000); timer.schedule(myTaskB, runDate1, 4000); } }
Timer's cancel() method
Different from the cancel() method in the TimerTask class that clears itself, the cancel() method in the Timer class is to clear all the tasks in the task queue. The task is cleared.
import java.util.Date; import java.util.TimerTask; public class MyTaskA extends TimerTask{ @Override public void run() { System.out.println("A run timer="+new Date()); this.cancel(); System.out.println("A任务自己移除自己"); } } import java.util.Date; import java.util.TimerTask; public class MyTaskB extends TimerTask{ @Override public void run() { System.out.println("B run timer="+new Date()); } } import java.util.Calendar; import java.util.Date; import java.util.Timer; public class Run { public static void main(String[] args){ System.out.println("当前时间为:"+new Date()); Calendar c = Calendar.getInstance(); Date runDate1 = c.getTime(); System.out.println("计划时间为:"+runDate1); MyTaskA myTaskA = new MyTaskA(); MyTaskB myTaskB = new MyTaskB(); Timer timer = new Timer(); timer.schedule(myTaskA, runDate1, 4000); timer.schedule(myTaskB, runDate1, 4000); } }
schedule(TimerTask task, long delay)
The function of this method is to use the current time when the schedule(TimerTask task, long delay) method is executed as the reference time. Execute a TimerTask task after delaying the specified number of milliseconds based on this time.
import java.util.Date; import java.util.TimerTask; public class MyTask extends TimerTask{ @Override public void run() { System.out.println("A run timer="+new Date()); } } import java.util.Calendar; import java.util.Date; import java.util.Timer; public class Run { public static void main(String[] args) throws InterruptedException{ System.out.println("当前时间为:"+new Date()); Calendar c = Calendar.getInstance(); Date runDate1 = c.getTime(); System.out.println("计划时间为:"+runDate1); MyTask myTask = new MyTask(); Timer timer = new Timer(); timer.schedule(myTask, 7000); // 计划任务延迟7秒后执行 Thread.sleep(10000); timer.cancel(); } }
More related articles and tutorials are recommended: java introductory tutorial
The above is the detailed content of Java thread Timer timer. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
