Explain Codes LogoExplain Codes Logo

Print "hello world" every X seconds

java
scheduling
task-execution
java-8
Nikita BarsukovbyNikita Barsukov·Mar 3, 2025
TLDR

A repeating "hello world" message every X seconds in Java can be achieved using ScheduledExecutorService and scheduleAtFixedRate.

import java.util.concurrent.*; public class HelloWorldPrinter { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); // "Hello World" - The Famous first words... echo every x seconds executor.scheduleAtFixedRate(() -> System.out.println("hello world"), 0, 10, TimeUnit.SECONDS); } }

Modify the 10 value to set your desired repetition interval. This simple setup prints "hello world" upon immediate start and repeats every X seconds.

Making sense of task scheduling

Recurring tasks are best handled by understanding scheduling in Java. In this section, we unpack the most powerful and efficient ways to print "hello world" every X seconds.

ScheduledExecutorService: Your trusted workhorse

The workhorse of managing and executing scheduled tasks in Java is ScheduledExecutorService. Fixed-rate execution is achieved by the use of scheduleAtFixedRate. Avoid Thread.sleep interference issues with this mighty tool.

Timer and TimerTask: Oldies but goodies

Timer and TimerTask classes, while traditionally used, still hold their worth for efficient task scheduling. Here's how:

import java.util.Timer; import java.util.TimerTask; public class HelloWorldTimer { public static void main(String[] args) { TimerTask task = new TimerTask() { public void run() { // As unchangeable as the rising sun. System.out.println("hello world"); } }; Timer timer = new Timer("Printer"); // Onwards, to infinity and beyond! Or at least every x seconds. timer.scheduleAtFixedRate(task, 0, 10*1000); } }

Avoid common pitfalls

Keep clear of nested loops to prevent resource drain. Prefer scheduler utilities over these. Thread.sleep within tasks can muddle scheduler's timing accuracy.

Deep dive into scheduled tasks

For deeper grasp, let's dissect Timer and ScheduledExecutorService:

Unwrapping Timer class

The Timer class sets tasks for future execution in a background thread. They can be one-time or repeated at regular intervals.

Nuts and bolts of ScheduledExecutorService

The ScheduledExecutorService under java.util.concurrent is the advanced player for executing concurrent tasks. Best for tasks requiring many simultaneous executions, and offers more flexibility in exception handling.

Deciding between Timer and ScheduledExecutorService

Match the task's complexity to the method. Timer fits the bill for simple tasks, while complex or CPU-demanding tasks favor ScheduledExecutorService.

Patterns for recurring tasks

For periodic tasks, catch and address any exceptions to prevent scheduler from ending execution. For concurrent tasks, use Executors.newScheduledThreadPool for better management and resource utilization.