Tickers in Karel

Our example demonstrates how to use timers for periodic tasks in Java. While Java doesn’t have a direct equivalent to Go’s tickers, we can achieve similar functionality using ScheduledExecutorService.

import java.util.concurrent.*;
import java.time.LocalDateTime;

public class Tickers {
    public static void main(String[] args) throws InterruptedException {
        // Create a ScheduledExecutorService with a single thread
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // Schedule a task to run every 500 milliseconds
        ScheduledFuture<?> ticker = scheduler.scheduleAtFixedRate(() -> {
            System.out.println("Tick at " + LocalDateTime.now());
        }, 0, 500, TimeUnit.MILLISECONDS);

        // Let it run for 1600 milliseconds
        Thread.sleep(1600);

        // Stop the ticker
        ticker.cancel(false);
        scheduler.shutdown();
        System.out.println("Ticker stopped");
    }
}

In this example, we use ScheduledExecutorService to create a task that runs periodically. Here’s how it works:

  1. We create a ScheduledExecutorService with a single thread.

  2. We schedule a task to run every 500 milliseconds using scheduleAtFixedRate. This is similar to creating a ticker in Go.

  3. The task simply prints the current time, simulating a “tick”.

  4. We let the program run for 1600 milliseconds using Thread.sleep.

  5. After 1600 milliseconds, we cancel the scheduled task and shut down the executor service.

When we run this program, the task should execute 3 times before we stop it:

$ javac Tickers.java
$ java Tickers
Tick at 2023-06-10T15:30:00.123
Tick at 2023-06-10T15:30:00.623
Tick at 2023-06-10T15:30:01.123
Ticker stopped

This Java implementation provides similar functionality to the Go example, using Java’s concurrency utilities to achieve periodic task execution.