Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a method in Spring Boot to execute at specific Date

Tags:

I have an "Ad" Entity in my database which has activeUntil field in it.

Now, i would like to create a method on my backend which will execute its logic on Date specified as value inside activeUntil property. Basically i want to send User which posted the Ad that it expired. Sadly i have no clue how to do that. Does Spring Boot provide anything like that? Thanks in advance!

like image 349
Stefan Radonjic Avatar asked Apr 07 '18 18:04

Stefan Radonjic


People also ask

How do I schedule a task in spring boot?

Java Cron ExpressionThe @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. The @Scheduled annotation is used to trigger the scheduler for a specific time period.


1 Answers

Use spring boot's built in scheduled task feature. You can use CRON format to specify what dates and times you want your specific function to run at.

The following example is being scheduled to run 15 minutes past each hour but only during the 9-to-5 "business hours" on weekdays.

scheduler.schedule(task, new CronTrigger("0 15 9-17 * * MON-FRI"));

In your particular case, your scheduled function would pull Ad entities from the DB which have expired and would run the method which you want to execute on each of the expired Ad entities.

See the docs for more information:

https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling

More on CRON syntax:

http://www.nncron.ru/help/EN/working/cron-format.htm

like image 90
Jake Miller Avatar answered Sep 19 '22 12:09

Jake Miller