Constantin Beer
Constantin Beer

Reputation: 5835

How to update value in db in given time interval in java?

I'm using a Spring Boot project with mariaDB as database server. I'm new to Spring and what I'm trying to do is to update specific columns in my db in a given time interval.

For example I got the following entity in my project:

PlayerResources.java

@Entity
@Table(name = "player_resources")
public class PlayerResources {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "metal")
    private BigDecimal metal;

    @Column(name = "plastic")
    private BigDecimal plastic;

    @Column(name = "information")
    private BigDecimal information;

    @Column(name = "technology")
    private BigDecimal technology;
...

And know I want to implement a method (or event?) in a service class that, let's say, updates the metal value every minute by 500. The actual value by which the metal value is to be increased will be provided through a formula that among other things contains the information about the date when the player was created. So the metal value must be increased depending on the date. If the player was created today at 08:34:54am (hh:mm:ss) then the first increase of the metal value should be 60 seconds after that time - 08:35:54am.

So something like this:

PseudoService

public class PseudoService {

   private int levelOfProduction;
   private int someOtherValueToNote;
   private Timestamp dateOfCreation;
   private int timeIntervallInMinutes;


   public int amountToIncreaseMetalEvent(int defaultMetalIncreaseValue) {
      return repeat(valueToIncrease(defaultMetalIncreaseValue + levelOfProduction * someOtherValueToNote), timeInterval(dateOfCreation, timeIntervallInMinutes))
   }

   private int repeat(valueToIncrease, timeIntervall) {
      ...
   }
}

I know that PseudoService makes no sense, but don't know how to clearify it better and hope someone understands what I'm trying to accomplish.

I already searched for other posts like that. But couldn't find something matching my problem.

My main goal is to create a game logic for a strategy game in which the player can produce resources and these resources should be updated in the player account every minute (or maybe another time intervall, e.g. seconds). And later on I want to provide through websockets the data to the frontend via Spring REST.

Upvotes: 0

Views: 1181

Answers (1)

lczapski
lczapski

Reputation: 4140

You can do something like this:

@Scheduled(cron="0 * * * * *")
public void doScheduledWork() {
    for (PlayerResources pr: findAllPlayerResources()) {
        // pr has to know how to find its player
        pr.setMetal(calculateNewMetalValueForGivenPlayer(pr)); 
        update(pr)    
    }
}

Upvotes: 1

Related Questions