How To Schedule Tasks Using Cron Job In A Play Application
Posted By : Gursahib Singh | 31-May-2018
Cron jobs are the jobs which are executed on the server after every fixed time interval.These are very commonly used in the development of the web application. Examples of cron jobs include checking or comparing data in the database, sending a message or a mail to the users periodically, updating summary tables in the database and fetching data from the database.
Adavantages of using cron jobs:
1. It does not occupy memory when it is not running i.e at the time when the cron jobs are scheduled to run than only they will occupy the memory.
2. Cron jobs can be controlled over a wide range of time interval like minutes,hours,days and much more.
3. It eleminates the use of looping for the events or the tasks which are required to be executed frequently.
Steps to use cron jobs in the play framework:
1. The cron jobs in a play application can be included in the Global.java file.The Global class extends GlobalSettings class so that all the global settings of the project can be configured here.
2. Override the onStart() method to include the code which is executed just after starting the application.
public class Global extends GlobalSettings {
public void onStart(Application app) {
Logger.info("Application has started");
}
3. Define the job in the onstart() method as follows:
Runnable sendSmsAfter1HOUR = new Runnable() {
@Override
public void run() {
//define the cron job
.
.
.
Logger.debug("sms sent...");
}
}
4. Define the delay, which is the time-delay after the start of the application for the cron jobs to get started.
FiniteDuration delay = FiniteDuration.create(5, TimeUnit.SECONDS);
5. Define the frequency, which is the duration or the time-interval after which the cron jobs are executed.
FiniteDuration frequency = FiniteDuration.create(1, TimeUnit.HOUR);
6. Schedule the event for a particular time interval.
Akka.system().scheduler().schedule(delay, frequency, sendSmsAfter1HOUR, Akka.system().dispatcher());
This is how cron jobs are scheduled in a play framework application.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Gursahib Singh
Gursahib is a software developer having key skills in J2SE and J2EE. His hobbies are playing chess, reading and learning new softwares.