简体   繁体   中英

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?

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);

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM