Skip to content
Bebras edited this page Jun 20, 2016 · 3 revisions

Timers

Shoebill provides two types for creating timers: Timer and TemporaryTimer*. The difference between them is that if you do not store a reference to Timer instance, it will be destroyed whereas instances of TemporaryTimer will only be destroyed after they complete their interval. As the name suggests Temporary Timers should be used for short/temporary tasks where stopping the timer isn't necessary.

* Note To use TemporaryTimer you need to add shoebill-common as a dependency in your project.

Timer creating

Java

public class TimerTest extends Plugin {
   
    private Timer minuteTimer;      
    private Timer hourlyTimer;
   
    public onEnable() throws Throwable {
        // 60000 = 60 * 1000 = 1 minute
        minuteTimer = Timer.create(60000, 1, (i) -> {
            getLogger().info("A minute has passed");
        });
        minuteTimer.start()
 
        hourlyTimer = Timer.create(60*60*1000, (i) -> {
            getLogger().info("An another hour has passed");
        });
        hourlyTimer.start();
    }

    public onDisable() throws Throwable {
        this.hourlyTimer.stop();
    }
}

Kotlin

class TimerTest: Plugin() {
    private lateinit var minuteTimer: Timer
    private lateinit var hourlyTimer: Timer

    override fun onEnable() {
        minuteTimer = Timer.create(60000, 1, { i -> 
            logger.info("A minute has passed")
        })
        minuteTimer.start()

        hourlyTimer = Timer.create(60*60*1000, { i -> 
            logger.info("An another hour has passed")
        })
        hourlyTimer.start()
    }

    override fun onDisable() {
        hourlyTimer.stop()
    }
}

The same result by using TemporaryTimer:

Java

public class TimerTest extends Plugin {
    
    public onEnable() throws Throwable {
        // 60000 = 60 * 1000 = 1 minute
        TemporaryTimer.create(60000, 1, (i) -> {
            getLogger().info("A minute has passed");
        }).start();
    
    
        TemporaryTimer.create(60*60*1000, (i) -> {
            getLogger().info("An another hour has passed");
        }).start();
    }
}

Kotlin

class TimerTest: Plugin() {
    override fun onEnable() {
        TemporaryTimer.create(60000, 1, { i -> 
            logger.info("A minute has passed")
        }).start()
    
        TemporaryTimer.create(60*60*1000, { i -> 
            logger.info("An another hour has passed")
        }).start()
    }
}

Now if there were no instance variables for minuteTimerand hourlyTimer they would be destroyed without finishing!

.create Arguments

Name Description
interval Time in milliseconds until the next execution of this timer
count Amount of times that the callback will be called(anything below 1 will make it run forever)
callback TimerCallback instance

Clone this wiki locally