简体   繁体   中英

Execute java code at specific time

I'm developing a soccer manager code that handles a game between friends where people need to compile their team and when real matches begin who has the players that play better wons the game.

Obviously, once the game has started, the players can't change their team anymore. On the database every match has an attribute "match is opened" that determines if the players still can change their team. Once the values is set false players can't edit their team anymore.

So basically I have a datetime and when that date occurs the value on the database has to be set to false.

I thought many alternatives I'm going to explain you:

  • Obviously the most dirty and naive is to log to the server, open the dbms and query the db to set the value to false. Very dirty solution.
  • Make a batch script and put it in the scheduled tasks. This solution too is very dirty as every week I get to log on the server to edit the script with the new date.
  • On the webapp make some control like: "When one of the users tries to edit his team, if the time has passed set the "open" attribute to false for everyone." This solutions seems to be dirty because until someone tries to change the formations and the system recognizes the problem, formations are de facto open.
  • Given a date, when the x hour arrives the code automatically launches a method that closes the teams.

The last one is the solution I'd prefer to develop, I know there are libs that allow to work with scheduling but I really don't know if stuff like that is possible and how would you develop this stuff.

Any hint will be appreciated.

Maybe the Quartz Framework might be interesting to you. It has a Job interface, which can be scheduled like Cron tasks.

Here is an example we use:

@Configuration
@EnableScheduling
public class SchedulerConfiguration {

   @Scheduled(cron = "15 * * * * ") //every 15 minutes
   public void scheduledTask() {
      doSomethingInYourDatabase();
   }

}

i would recommend whether to use spring scheduler (if you are using spring) or a simple java executor service to run aa method with lets say 5 minutes delay after the previous execution. have a look here http://tutorials.jenkov.com/java-util-concurrent/executorservice.html

In fact you will just need to run a simple update query like

update match set match_open = false where start_time = (Sysdate-X);

May be you are using spring. you can add a Service class (@Service) and use @Scheduled annotated method which will help you execute a task at defined interval. Check details spring schedulling

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
    //something that should execute on weekdays only
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM