Reputation:
I have a method in one of my model classes that removes model objects whose date field is out-of-date. I was wondering if there anyway to automatically run this method every 24 hours for example? Sort of my like an in-system cronjob for my play application.
I am using play 2.0.4 - here is the model method:
public static void removeHistoricDates() throws ParseException {
List<Book> allBooks = new ArrayList<Book>();
allBooks = find.all();
//Empty-list that out-of-date Books will be added to
List<Book> historicDates = new ArrayList<Book>();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
for(Book Book: allBooks) {
Date BookDate = formatter.parse(Book.date);
Date todayDate = new Date();
if(todayDate.after(BookDate)) {
historicDates.add(Book);
}
}
for(Book outofDate: historicDates) {
find.ref(outofDate.id).delete();
}
}
At the moment I am just invoking this method whenever I call a method in my controllers/Application to prove that it works - and it does. What I would hope to do would be call this model method independently every 24 hours without relying on a certain application method being invoked by a user.
Update: So at the moment I am looking at this as Heroku is the hosting service I am using.
Upvotes: 1
Views: 196
Reputation: 18446
Easy as pie! Play relies on Akka to schedule tasks. Check out the corresponding page in the docs and the Akka docs on the Scheduler.
You'll want to do something like this:
Akka.system().scheduler().schedule(
Duration.create(24, TimeUnit.HOURS),
new Runnable() {
public void run() {
// your code here.
}
}
);
Upvotes: 3