[Java] How to execute tasks on a regular basis

Introduction

This time, I will explain how to execute tasks regularly in Java. This function is often used in batch processing.

In the sample, we will use the Timer class to implement the process of executing tasks on a regular basis.

Then I will explain it immediately.

1. Development environment

After that, it will be explained in the following versions and environments.

IDE:eclipse Java version: 8

2. Folder structure

The folder structure of this sample program is as follows. スクリーンショット 2018-11-14 21.02.27.png

3. Implementation of sample program

3-1. Implementation of tasks that you want to execute on a regular basis

Implement tasks that you want to execute on a regular basis using the TimerTask class. This time, we will implement a sample process that periodically outputs "The task has been executed" to the console.

Main.java


package main;
//The part to be added this time
import java.util.TimerTask;

public class Main {
    public static void main(String[] args) {
        //The part to be added this time
        TimerTask task = new TimerTask() {
            public void run() {
                //Processing that you want to execute on a regular basis
                System.out.println("The task has been executed.");
            }
        };
    }
}

Also, in order to check how many times it has been executed, let's implement it so that you can see the number of times as follows.

Main.java


package main;

import java.util.TimerTask;

public class Main {
    public static void main(String[] args) {

        TimerTask task = new TimerTask() {
            int count = 0; //Processing to be added this time
            public void run() {
                //Processing that you want to execute on a regular basis
                count++; //Processing to be added this time
                System.out.println(count + "The second task has been performed."); //Processing to be corrected this time
            }
        };
    }
}

3-2. Implementation of schedule

Next, we will implement when to start executing the task and how often to execute the task.

As for the implementation method, use the scheduleAtFixedRate method of the Timer class. The usage is as follows.

Timer timer = new Timer();
timer.scheduleAtFixedRate(Tasks you want to perform on a regular basis,Time to execute the first task(ms),Interval between tasks to perform(ms));

Although it is the second argument of the scheduleAtFixedRate method, not only "time until the first task execution" but also "task start time" can be specified by Date type.

In this sample, we will implement the process that the task is executed at 3 second intervals 1 second after PGM is executed.

Main.java


package main;

import java.util.Timer; //Processing to be added this time
import java.util.TimerTask;

public class Main {
    public static void main(String[] args) {

        Timer timer = new Timer(); //Processing to be added this time
        TimerTask task = new TimerTask() {
            int count = 0;
            public void run() {
                //Processing that you want to execute on a regular basis
                count++;
                System.out.println(count + "The second task has been performed.");
            }
        };
        timer.scheduleAtFixedRate(task,1000,3000); //Processing to be added this time
    }
}

After completing the above implementation, right-click Main.java> Run Java Application to execute it.

It is OK if the following words are output to the console at 3 second intervals.

console


The first task has been performed.
The second task has been performed.
The third task has been performed.
The fourth task has been performed.
・ ・ ・

at the end

I started my personal blog in 2020!

Based on the knowledge and experience gained as a freelance engineer, we plan to distribute content such as information on freelance engineers, IT technical information, industry information, and engineer life hacks.

The number of articles is still small, but it is updated weekly, so if you are interested, I would be grateful if you could take a look.

https://yacchi-engineer.com/

Recommended Posts

[Java] How to execute tasks on a regular basis
Notes on how to use regular expressions in Java
[Java] How to update Java on Windows
How to make a Java container
[Java] How to create a folder
How to make a Java array
How to deploy a simple Java Servlet app on Heroku
How to deploy a kotlin (java) app on AWS fargate
How to check Java installed on Mac
How to execute a contract using web3j
How to execute Postgresql copy command with column information on Java
How to switch Java versions on Mac
How to make a Discord bot (Java)
How to print a Java Word document
How to deploy a container on AWS Lambda
How to display a web page in Java
[Ethereum] How to execute a contract using web3j-Part 2-
How to execute tasks in parallel in Swift in Swift Package
How to build a Pytorch environment on Ubuntu
[Java] Memo on how to write the source
How to create a Java environment in just 3 seconds
How to jump from Eclipse Java to a SQL file
How to use java non-standard library on IntelliJ IDEA
java: How to write a generic type list [Note]
[Java] How to play rock-paper-scissors (equivalent to paiza rank A)
How to make JavaScript work on a specific page
How to create a data URI (base64) in Java
[Java] How to get a request by HTTP communication
As of April 2018 How to get Java 8 on Mac
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
How to run Java EE Tutial on github on Eclipse
How to execute WebCamCapture sample of NyARToolkit for Java
[Ruby/Rails] How to generate a password in a regular expression
[Java] How to start a new line with StringBuilder
[Java] How to use Map
How to lower java version
[Java] How to use Map
How to uninstall Java 8 (Mac)
How to use java Optional
[java tool] A useful tool when you want to send the ipmsg log of PC-A to the specified PC on a regular basis.
How to deploy on heroku
How to minimize Java images
How to write java comments
How to leave a comment
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] How to use string.format
How to use Java Map
How to set Java constants
How to use Java variables
How to convert Java radix
[Java] How to implement multithreading
[Java] How to use Optional ①
How to initialize Java array
How to insert a video
How to create a method