JME
JME

Reputation: 2363

Creating a recurring timer

I have been tasked with creating a Java version of a C# SDK. Currently. I am working on a class that extends the C# System.ServiceProcess.ServiceBase but due to the difficulty of creating Windows services in Java I am focusing on some of the other methods in the class.

The current C# method I am attempting to replicate in Java looks as follows

    private void StartProcesses()
    {
        // create a new cancellationtoken souce
        _cts = new CancellationTokenSource();

        // start the window timer
        _windowTimer = new Timer(new TimerCallback(WindowCallback),
            _cts.Token, 0, Convert.ToInt64(this.SQSWindow.TotalMilliseconds));

        this.IsWindowing = true;
    }

After analyzing this section of code I believe that it initializes a System.threading.Timer object that executes the WindowCallback function every SQSWindow milliseconds.

After reading through the java.util.concurrent documentation located

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

I am unsure how I would replicate the C# functionality in Java as I cannot find the equivalent to the Timer functionality. The TimeUnit provided by the Java library appears to be only used for thread timeouts and not to issue recurring operations.

I am also curious as to the use of the CancellationTokenSource. If this object is meant to be queried to determine if the action is to continue, why is it not a primative such as a boolean? What additional functionality does it provide, and is there a similar construct in Java's multithreading model?

Upvotes: 1

Views: 1263

Answers (3)

assylias
assylias

Reputation: 328923

Using a ScheduledThreadPoolExecutor, you can get very similar functionality:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Runnable task = new Runnable() {
    public void run() {
        //here the code that needs to run periodically
    }
};
//run the task every 200 ms from now
Future<?> future = scheduler.scheduleAtFixedRate(task, 0, 200, TimeUnit.MILLISECONDS);
//a bit later, you want to cancel the scheduled task:
future.cancel(true);

Upvotes: 2

greedybuddha
greedybuddha

Reputation: 7507

The equivalent Java classes are `Timer and TimerTask.

Example:

Timer t = new Timer();
t.schedule(new TimerTask(){

    @Override
    public void run() {
        // Do stuff
    }

}, startTime, repeatEvery);

If you want to be able to cancel, then use the TimerTask as a variable. The TimerTask class has the method cancel.

Upvotes: 1

fge
fge

Reputation: 121840

You may want to have a look at ScheduledThreadPoolExecutor. It is an implementation of ScheduledExecutorService, which has the ability to schedule periodically.

Upvotes: 1

Related Questions