SoFunction
Updated on 2025-04-23

Complete analysis of the usage methods of Timer and TimerTask in Java

Preface

In Java programming, timing tasks are a common requirement. Whether it is performing certain operations regularly or performing tasks at a specific point in time, Java providesTimerandTimerTaskClasses can help us implement these functions easily. Today we will introduce in detail how to use these two classes, including execution and pause of tasks.

Understand Timer and TimerTask

TimerIs a class that can schedule tasks to be executed at a specified time or periodically.TimerTaskis an abstract class that represents the task to be executed regularly. useTimerWhen we need to inheritTimerTaskand realize itrunMethod, define specific task logic.

Create timers and timing tasks

Before we start, we create a simple timing task. First, you need to import the relevant packages:

import ;
import ;

Next, create an inheritanceTimerTaskclass and rewriterunmethod:

public class MyTask extends TimerTask {
    @Override
    public void run() {
        ("Timed task execution: " + ());
    }
}

In this example,runThe specific logic of the task is defined in the method, and here it is simply printing the current time.

Use Timer to schedule tasks

Now, it is availableTimerTo arrange the execution of this task. Create aTimerobject, and usescheduleMethod to schedule tasks:

public class TimerExample {
    public static void main(String[] args) {
        Timer timer = new Timer();
        MyTask task = new MyTask();
        
        // Schedule the task to start execution after 1 second, and execute it every 2 seconds        (task, 1000, 2000);
    }
}

In this example,scheduleThe first parameter of the method is the task to be executed, the second parameter is the delay time (milliseconds), and the third parameter is the period of the task (milliseconds). This task will start after 1 second and will be executed every 2 seconds.

Cancel the scheduled task

In some cases, we may need to cancel the timing task. useTimerofcancelMethods can cancel all tasks. Here is an example of how to cancel a timing task under certain conditions:

public class TimerWithCancel {
    public static void main(String[] args) {
        Timer timer = new Timer();
        MyTask task = new MyTask();
        
        (task, 1000, 2000);

        // Cancel the task after 5 seconds        try {
            (5000);
        } catch (InterruptedException e) {
            ();
        }
        
        ();
        ("Timed task cancelled");
    }
}

In this example, the program will cancel the timing task after 5 seconds.

Implement the task pause function

TimerandTimerTaskIt does not support direct pause and resume tasks, but we can implement this function with some tips. We can set a flag to control the execution of the task. The specific implementation methods are as follows:

public class PausableTask extends TimerTask {
    private volatile boolean isPaused = false;

    @Override
    public void run() {
        while (true) {
            if (isPaused) {
                synchronized (this) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        ();
                    }
                }
            }
            ("Execute Task: " + ());
            try {
                (1000); // Simulate task execution time            } catch (InterruptedException e) {
                ();
            }
        }
    }

    public void pause() {
        isPaused = true;
    }

    public synchronized void resume() {
        isPaused = false;
        notify();
    }
}

In thisPausableTaskIn the class, we use oneisPausedFlag bits to control the execution of tasks.runPassed in the methodwhileThe loop continuously checks this flag bit iftrue, will wait to be awakened.

Create a timer and control pause and recovery

Now, a timer can be created and the task pause and recovery can be achieved through the controller. As shown below:

public class TimerWithPauseResume {
    public static void main(String[] args) {
        Timer timer = new Timer();
        PausableTask task = new PausableTask();
        
        (task, 0);
        
        try {
            (5000); // Run for 5 seconds            ();
            ("Task Paused");
            (5000); // Pause for 5 seconds            ();
            ("Task resumed");
        } catch (InterruptedException e) {
            ();
        }
    }
}

In this example, the task will be executed for 5 seconds, then paused for 5 seconds, before resumed execution. In this way, we implement the pause and recovery functions of tasks.

Things to note

In useTimerandTimerTaskThere are a few points to note when:

  • Task execution time: If a task's execution time exceeds its cycle, it may cause task accumulation. Consider using ScheduledExecutorService instead of Timer.

  • Thread safetyTimerTaskofrunThe method is executed in the Timer worker thread to ensure that the code in it is thread-safe.

  • Exception handling:ifTimerTaskIn-houserunThe method throws an uncaught exception and Timer will terminate all tasks. Make sure that exceptions are caught and handled in the task.

in conclusion

Through the above introduction, we have learned in Java in detailTimerandTimerTaskThe use of timed tasks includes the creation, cancellation, pause and recovery functions. These functions allow us to flexibly control the execution of tasks and meet different needs. In actual projects, rational use of these tools can greatly simplify the management of timing tasks and improve the readability and maintainability of code.

This is the article about how to use timer Timer and TimerTask in Java. For more related content on using Java timer Timer and TimerTask, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!