Examples of timers and scheduled tasks in Java
This article mainly introduces examples of Timer and TimerTask timers and scheduled tasks in Java. It is of great practical value. Friends in need can refer to it.
These two classes are very convenient to use and can Complete most of our needs for timers
The Timer class is a class used to execute tasks. It accepts a TimerTask as a parameter
Timer has two modes for executing tasks, the most commonly used It is schedule, which can execute tasks in two ways: 1: at a certain time (Data), 2: after a fixed time (int delay). Both methods can specify the frequency of task execution
TimerTest.Java:
package com.cn; import java.io.IOException; import java.util.Timer; public class TimerTest{ public static void main(String[] args){ Timer timer = new Timer(); timer.schedule(new MyTask(), 1000, 2000);//在1秒后执行此任务,每次间隔2秒执行一次,如果传递一个Data参数,就可以在某个固定的时间执行这个任务. while(true){//这个是用来停止此任务的,否则就一直循环执行此任务 try{ int in = System.in.read(); if(in == 's'){ timer.cancel();//使用这个方法退出任务 break; } } catch (IOException e){ // TODO Auto-generated catch block e.printStackTrace(); } } } static class MyTask extends java.util.TimerTask{ public void run(){ System.out.println(""); } } }
This type of runtime:
Print "————" on the console 1 second after the program starts
After an interval of two seconds Then execute the run() method of MyTask and print "————"
This keeps looping
When the s character is entered on the console, the timer cancels the work
Jumps out of the entire loop
The program runs Finish!
TimerTest2.java:
package com.cn; import java.io.IOException; import java.util.Date; import java.util.Timer; public class TimerTest2{ public static void main(String[] args){ Timer timer = new Timer(); MyTask myTask1 = new MyTask(); MyTask myTask2 = new MyTask(); myTask2.setInfo("myTask-info-2"); timer.schedule(myTask1, 1000, 2000); //任务1 一秒钟后执行,每两秒执行一次。 timer.scheduleAtFixedRate(myTask2, 2000, 3000); //任务2 2秒后开始进行重复的固定速率执行(3秒钟重复一次) while (true){ try{ //用来接收键盘输入的字符串 byte[] info = new byte[1024]; int len = System.in.read(info); String strInfo = new String(info, 0, len, "GBK");//从控制台读出信息 if (strInfo.charAt(strInfo.length() - 1) == ' '){ strInfo = strInfo.substring(0, strInfo.length() - 2); } if (strInfo.startsWith("Cancel-1")){ myTask1.cancel();//退出任务1 // 其实应该在这里判断myTask2是否也退出了,是的话就应该break.但是因为无法在包外得到 // myTask2的状态,所以,这里不能做出是否退出循环的判断. } else if (strInfo.startsWith("Cancel-2")){ myTask2.cancel(); //退出任务2 } else if (strInfo.startsWith("Cancel-All")){ timer.cancel();//退出Timer break; } else{ // 只对myTask1作出判断,偷个懒^_^ myTask1.setInfo(strInfo); } } catch (IOException e){ // TODO Auto-generated catch block e.printStackTrace(); } } } static class MyTask extends java.util.TimerTask{ String info = "INFO"; @Override public void run(){ // TODO Auto-generated method stub System.out.println(new Date() + " " + info); } public String getInfo(){ return info; } public void setInfo(String info){ this.info = info; } } }
This class creates two scheduled tasks, mytask1 and mytask2.
The mytask1 task is used in the same way as the example in the TimerTest class above. That is, the specified task is scheduled to be executed with a fixed delay repeatedly starting from the specified delay.
The mytask2 task is different from the above usage. timer.scheduleAtFixedRate is executed using the scheduleAtFixedRate() method of the timer timer.
scheduleAtFixedRate() method is defined as follows in API1.6.0:
Schedule the specified task to start repeating at the specified time Executed at a fixed rate. Subsequent executions occur at approximately fixed intervals, separated by the specified period.
Approximately fixed time intervals mean that in fixed-rate execution, each execution is scheduled relative to the scheduled initial execution time. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in quick succession, allowing subsequent executions to catch up.
Other commonly used methods of the Timer class:
##cancel()
purge()
queue.
schedule(TimerTask task, Date time)
cancel()
run()
scheduledExecutionTime()
Special Recommendation: "php Programmer Toolbox" V0.1 version download
2. 3.The above is the detailed content of Examples of timers and scheduled tasks in Java. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Summary of some reasons why crontab scheduled tasks are not executed. Update time: January 9, 2019 09:34:57 Author: Hope on the field. This article mainly summarizes and introduces to you some reasons why crontab scheduled tasks are not executed. For everyone Solutions are given for each of the possible triggers, which have certain reference and learning value for colleagues who encounter this problem. Students in need can follow the editor to learn together. Preface: I have encountered some problems at work recently. The crontab scheduled task was not executed. Later, when I searched on the Internet, I found that the Internet mainly mentioned these five incentives: 1. The crond service is not started. Crontab is not a function of the Linux kernel, but relies on a cron.

ThinkPHP6 scheduled task scheduling: scheduled task execution 1. Introduction In the process of web application development, we often encounter situations where certain repetitive tasks need to be executed regularly. ThinkPHP6 provides a powerful scheduled task scheduling function, which can easily meet the needs of scheduled tasks. This article will introduce how to use scheduled task scheduling in ThinkPHP6, and provide some code examples to help understand. 2. Configure scheduled tasks, create scheduled task files, and create a comman in the app directory of the project.

In web development, many websites and applications need to perform certain tasks regularly, such as cleaning up junk data, sending emails, etc. In order to automate these tasks, developers need to implement task scheduling and timed task functions. This article will introduce how to implement task scheduling and timed tasks in PHP, as well as some commonly used third-party libraries and tools. 1. Task Scheduling Task scheduling refers to executing certain tasks according to specified times or events. In PHP, cron timer or similar mechanism can be used to implement task scheduling. Typically, task scheduling

Python implements automatic page refresh and scheduled task function analysis for headless browser collection applications. With the rapid development of the network and the popularization of applications, the collection of web page data has become more and more important. The headless browser is one of the effective tools for collecting web page data. This article will introduce how to use Python to implement the automatic page refresh and scheduled task functions of a headless browser. The headless browser adopts a browser operation mode without a graphical interface, which can simulate human operation behavior in an automated way, thereby enabling the user to access web pages, click buttons, and fill in information.

How to use scheduled tasks in FastAPI to perform background work. With the rapid development of Internet applications, many applications have some background tasks that need to be executed regularly, such as data cleaning, email sending, backup, etc. In order to solve this problem, we can use scheduled tasks to automatically execute background work. In this article, we will introduce how to use scheduled tasks in the FastAPI framework to perform background work. FastAPI is a modern, fast (high-performance) web framework mainly used for building APIs. it has

How to use PHP to develop a scheduled refresh function for web pages. With the development of the Internet, more and more websites need to update display data in real time. Refreshing the page in real time is a common requirement, which allows users to obtain the latest data without refreshing the entire page. This article will introduce how to use PHP to develop a scheduled refresh function for web pages and provide code examples. The simplest way to implement scheduled refresh using Meta tag is to use HTML Meta tag to refresh the page regularly. In HTML<head>

SpringBoot is a very popular Java development framework. It not only has the advantage of rapid development, but also has many built-in practical functions. Among them, task scheduling and scheduled tasks are one of its commonly used functions. This article will explore SpringBoot's task scheduling and timing task implementation methods. 1. Introduction to SpringBoot task scheduling SpringBoot task scheduling (TaskScheduling) refers to executing some special tasks at a specific point in time or under certain conditions.

How to implement scheduled tasks and periodic tasks in FastAPI Introduction: FastAPI is a modern, highly performant Python framework focused on building API applications. However, sometimes we need to perform scheduled tasks and periodic tasks in FastAPI applications. This article describes how to implement these tasks in a FastAPI application and provides corresponding code examples. 1. Implementation of scheduled tasks using APScheduler library APScheduler is a function
