SoFunction
Updated on 2025-03-06

Four ways to implement timers in Java

There are many ways to implement timers in Java. This article mainly introduces several ways I know

Method 1: Use Timer and TimerTask classes

1. Timer and TimerTask are classes under the package, used to implement timing tasks

  • Step 1: Create TimerTask timer task, which can be created through anonymous internal class
  • Step 2: Create a Timer timer and call the timer method to execute the timer task

2. Timer's two methods schedule() and scheduleAtFixedRate() and their overloaded methods:

  • void schedule(TimerTask task, long delay): Execute one task after the specified time, where delay represents the delay, the unit is milliseconds, set to 1000, which means that a timer task is executed after 1 second;
  • void schedule(TimerTask task, long delay, long period): Specify the delay and execute the task periodically after the specified time (after delay milliseconds, it will be executed once every milliseconds)
  • void scheduleAtFixedRate(TimerTask task, long delay, long period): Specify the delay and execute the task periodically after the specified time (after delay milliseconds, it will be executed once every milliseconds)
  • void scheduleAtFixedRate(TimerTask task, Date firstTime, long period): Starting from the specified date, the task is executed every milliseconds

3. Case code

public class TimerExample {

    public static void main(String[] args) {
        // Create a timer        Timer timer = new Timer();
        // Create a timer task        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                ("Hello world!");
            }
        };

        (task, 1000); // Execute once in 1 second        (task, 2000, 2000); // Execute every two seconds after two seconds        (task, 3000, 3000); // Execute every 3 seconds after 3 seconds        (task, new Date(), 4000); // Execute every 4 seconds    }

}

Method 2: Use thread pool

The thread pool method is the same as Timer. TimeUnit is an enumeration type used to specify time units, including NANOSECONDS (nanoseconds), MICROSECONDS (microseconds), MILISECONDS (milliseconds), SECONDS (seconds), MINUTE (minutes), HOURS (hours) and DAYS (days).

Case code:

public class TimerExample {
    public static void main(String[] args) {
        // Create a timer task        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                ("Hello world!");
            }
        };

        ScheduledExecutorService scheduledThreadPool = (2);

        (timerTask, 1000, );
        (timerTask, 1000, 1000, );
    }

}

Method 3: Use Spring Task

Step 1: Add @EnableScheduling annotation on springBoot startup class

@EnableScheduling
@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        (, args);
    }

}

Step 2: Create a bean of the timed task class, use @Schedule annotation on the class method, and set the attributes of the timer through the cron attribute of the annotation

@Component
public class TimerTask {

    @Scheduled(cron = "0 7 2 26 7 *")
    public void task() {
        ("Timed tasks...");
    }

}

The above code specifies that a timed task will be executed at 02:07:00 on July 26, 2022. Those who are interested in cron expressions can learn about it. I won’t introduce it here.

Method 4: Use Quartz Task Scheduling Tool

Step 1: Add quartz's dependencies in

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

Step 2: Define the Job

public class QuartzJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        // Output the current time        (());
    }

}

Step 3: Create quartz's configuration class

@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail jobDetail() {
        return ()   // Bind the class object of the task class to be run                .withIdentity("job")                // Set the job name                .storeDurably()                     // Information lasts                // After setting storeDurably, when no trigger points to this JobDetail, the JobDetail will not be from                // Delete from the Spring container. If this line is not set, it will be automatically deleted from the Spring container.                .build();
    }

    @Bean
    public Trigger trigger() {
        // Define Cron expression, triggered every 10 seconds        CronScheduleBuilder cronScheduleBuilder = 
                ("0/10 * * * * ?");
        
        return ()
                .forJob(jobDetail())                 // Bind the JobDetail object                .withIdentity("trigger")             // Define the trigger name                .withSchedule(cronScheduleBuilder)   // Bind Cron expression                .build();
    }

}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.