How to Efficiently Schedule Tasks in Kotlin & Ktor: A Complete Step-by-Step Guide
What is task scheduling in Kotlin Or Ktor Or in general?
- Scheduling a task simply means to have a functionality executed at a particular date and time in periodic interval.
- Like scheduling a task that will run at 12 AM night everyday.
- Task that will run at 1st of every month and perform some operations.
- Or a task that will run every 2 hours and deletes some data from the database etc.
- All these are nothing but Scheduled Tasks, that will be executed based on how they are configured.
Ktor has its own advantages and disadvantages:
Advantages of Ktor:
Some Disadvantages of Ktor:
Can we schedule tasks in Kotlin or Ktor?
How To Schedule tasks in Kotlin or Ktor?
-
Yes and No, yup you read it right, we can schedule tasks in Kotlin/Ktor
but there is no specified library that we can use here like we used to get
in other framework like spring boot.
How to schedule tasks in Kotlin Or Ktor?
- As Kotlin/Ktor does have any inbuilt library's that we can use to schedule any tasks.
- We can use the other classes like Timer and configure it in such a way that we can make it work as a scheduler in kotlin or ktor.
In this post we will discuss few ways in which we can schedule tasks in kotlin or ktor. These are also known as Schedulers in Kotlin.
Scheduling a Task in Kotlin / Ktor that will run periodically.
- task – task to be scheduled.
- delay – delay in milliseconds before task is to be executed.
- period – time in milliseconds between successive task executions.
scheduleAtFixedRate() : This function schedules the task we pass in the argument for repeated fixed-rate execution, beginning after the specified delay. All subsequent executions take place at approximately regular intervals, separated by the specified period.
If code is not visible properly, kindly rotate the mobile screen.
Schedule task in particular interval of minutes kotlin code:
/**
* This function schedules a task instantly
* when the function is called.
* @param periodicIntervalInMinutes :
* The interval time for
* running the task periodically
* */
fun scheduleInstantlyAtInterval(
periodicIntervalInMinutes: Int
)
{
println("Setting up the Scheduler.")
val periodicIntervalTimeInMilliSeconds =
periodicIntervalInMinutes * 60 * 1000
Timer().scheduleAtFixedRate(
timerTask {
println("Scheduled task started.")
performTheTask()
println("Scheduled task complete.")
},
0L,
periodicIntervalTimeInMilliSeconds
.toLong()
)
println("Scheduler Set up Successfully.")
}
fun performTheTask() {
/**
* This is fixed rate instant started
* scheduled tasks in Kotlin or Ktor
* by KodeSrc!
* */
println("Scheduled Task in kotlin by KodeSrc")
}
This method takes the interval in which we want to schedule our tasks and will run instantly for the first time as soon as the method is called and then will be scheduled at fixed rate for given interval of time.
Main Method:
fun main() {
println("Inside Main.")
scheduleInstantlyAtInterval(1)
}
Output:
This way we can create a scheduler in kotlin that will run after every 1 minute and perform the operation that needs to be performed.
But what if you need to run the task at a particular time of a day say 6 AM in morning or 12 AM at night.
How to schedule a task in kotlin or ktor that will run everyday at specified time ?
To Schedule tasks at a particular time of a day we can use the Calendar class.
Kotlin Code Of Scheduler 24 hrs periodic:
/**
* This function will schedule a task at the given time
* and execute it every day at that particular time.
*
* @param hour: hours will be in 24 hr format
* @param minute: minutes
* @param second: seconds
* */
fun scheduleATask(
hour: Int,
minute: Int,
second: Int
)
{
println("Setting up the scheduler.")
//Get currentTime
val currentTime = Calendar.getInstance()
println("currentTime:${currentTime.time}")
//set the schedulerTime from the input request
val schedulerTime = Calendar.getInstance()
schedulerTime[Calendar.HOUR_OF_DAY] = hour
schedulerTime[Calendar.MINUTE] = minute
schedulerTime[Calendar.SECOND] = second
println("schedulerTime:${schedulerTime.time}")
/* Calculate the initial delay this delay
will be used to trigger the task for 1st time.
the difference between the two times will be our initialDelay.
*/
var initialDelay =
schedulerTime.timeInMillis - currentTime.timeInMillis
val regularRunInterval = 86400000L
//Create the scheduler
Timer().scheduleAtFixedRate(timerTask {
performTheTask()
}, initialDelay, regularRunInterval)
println("Scheduler Set Successfully.")
}
fun performTheTask() {
/**
* This is fixed rate instant started
* scheduled tasks in Kotlin or Ktor
* by KodeSrc!
* */
println("Scheduled Task in kotlin by KodeSrc")
}
But hold on a second !! What if the time you want to schedule a task is passed way? Will it still work? If not what is better alternative?
The Answer is above code will not work in such cases as the initialDelay would come up to be negative and even if you get a absolute value of the difference it will still not work as we want it to be work.
Is there any better way?
Yes ! We will run the job next day if the time has already passed simple as that !!
We will have a check and if the time is passed we will add 1 more day to the initialDelay so that the task is scheduled for the next day.
Kotlin Code Of Scheduler 1 day increment:
/**
* This function will schedule a task at the given time
* and execute it every day at that particular time.
*
* @param hour: hours will be in 24 hr format
* @param minute: minutes
* @param second: seconds
**/
fun scheduleATask(
hour: Int,
minute: Int,
second: Int
)
{
println("Setting up the scheduler.")
//Get currentTime
val currentTime = Calendar.getInstance()
println("currentTime:${currentTime.time}")
//set the schedulerTime from the input request
val schedulerTime = Calendar.getInstance()
schedulerTime[Calendar.HOUR_OF_DAY] = hour
schedulerTime[Calendar.MINUTE] = minute
schedulerTime[Calendar.SECOND] = second
println("schedulerTime:${schedulerTime.time}")
/* Calculate the initial delay this delay
will be used to trigger the task for 1st time.
the difference between the two times will be our initialDelay.
*/
var initialDelay =
schedulerTime.timeInMillis - currentTime.timeInMillis
/*
* Inorder to make sure the task runs at the given time
* make sure initialDelay is positive number
* if initialDelay is negative that means the
* time is passed away we should run the job
* next day
* */
if (initialDelay < 0) {
println("Your provided time has passed.")
//This will set the time to next day
schedulerTime[Calendar.HOUR_OF_DAY] =
schedulerTime[Calendar.HOUR_OF_DAY] + 24
initialDelay =
schedulerTime.timeInMillis-currentTime.timeInMillis
println(
"Your task will now run at: " +
"${schedulerTime.time}"
)
}
val regularRunInterval = 86400000L
//Create the scheduler
Timer().scheduleAtFixedRate(timerTask {
performTheTask()
}, initialDelay, regularRunInterval)
println("Scheduler Set Successfully.")
}
fun performTheTask() {
/**
* This is fixed rate instant started
* scheduled tasks in Kotlin or Ktor
* by KodeSrc!
* */
println("Scheduled Task in kotlin by KodeSrc")
}
fun main() {
println("Inside Main.")
scheduleATask(12, 30, 0)
}
Output:
If request time not passed:
If requested time is passed:
As you can see the task is now scheduled for next day at that particular time.
Please Let me Know, If you have any doubts.
Please Let me Know, If you have any doubts.