Tickers in Miranda

Our example demonstrates the use of tickers, which are used for executing tasks repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

import java.util.Timer;
import java.util.TimerTask;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Tickers {
    public static void main(String[] args) {
        // Tickers in Java can be implemented using Timer and TimerTask
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
                System.out.println("Tick at " + now.format(formatter));
            }
        };

        // Schedule the task to run every 500 milliseconds
        timer.scheduleAtFixedRate(task, 0, 500);

        try {
            // Let the ticker run for 1600 milliseconds
            Thread.sleep(1600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

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

In this Java implementation, we use a Timer and TimerTask to simulate the behavior of a ticker. The Timer schedules the TimerTask to run every 500 milliseconds.

We let the ticker run for 1600 milliseconds using Thread.sleep(), and then stop it using timer.cancel().

When we run this program, the ticker should tick 3 times before we stop it.

$ java Tickers
Tick at 2023-05-10 15:30:00.123
Tick at 2023-05-10 15:30:00.623
Tick at 2023-05-10 15:30:01.123
Ticker stopped

This example demonstrates how to create and use tickers in Java for executing tasks at regular intervals. The Timer and TimerTask classes provide similar functionality to tickers in other languages, allowing you to schedule repeated executions of a task.