Solved MySQL - Effective way of storing player time

Discussion in 'Plugin Development' started by xDeeKay, Jan 13, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    xDeeKay

    So here's yet another MySQL based question. I want to store players total online time in a MySQL database, and I've thought of 2 ways of doing this, but I need to know which is more efficient/effective, or maybe if there's another way.

    Option 1: When a player logs in, create a hashmap for that player, and every x amount of time (most likely in seconds), add 1 to their hashmap. When they logout, write that hashmap amount to the database.

    Option 2: When a player logs in, store the time via System.currentTimeMillis() to that player. When they logout, get the difference again using System.currentTimeMillis() and write that to the database.

    Does anyone have any other ideas?
     
  2. Offline

    API_Tutorials

    @xDeeKay
    Option 2 would probably be the most efficient.
     
    es359 likes this.
  3. Offline

    xDeeKay

    @API_Tutorials Yeah I figured this would be. I went ahead and used option 2 and it's saved me a lot of headache. For anyone else that stumbles across this thread, here's what I did:

    1. Created a hashmap to store the servers time when a player logs in, for that player.
    Code:
    public final static HashMap<String, Long> statsTimeOnline = new HashMap<String, Long>();
    2. Defined what the difference in time is. In my case I want it in seconds, so it's the current server time minus the time stored in their hashmap divided by 1000.
    Code:
    final long diffInSec = (System.currentTimeMillis() - Main.statsTimeOnline.get(playerName)) / 1000;
    3. When the player logs out, I run a task asynchronously which writes the diffInSec to the defined table using a prepared statement.
    Code:
    previousTimeOnline = result.getInt("time_online");
    
    PreparedStatement timeUpdate = Main.connection
            .prepareStatement("UPDATE `player_stats` SET time_online=? WHERE uuid=?;");
    timeUpdate.setLong(1, previousTimeOnline + diffInSec);
    timeUpdate.setString(2, uuid);
    timeUpdate.executeUpdate();
    
    timeUpdate.close();
    4. And of course remove them from the hashmap and do any other necessary changes.
     
    API_Tutorials likes this.
  4. Offline

    API_Tutorials

    @xDeeKay
    Please mark the thread as solved
     
  5. Offline

    nverdier

  6. Offline

    unrealdesign

  7. Offline

    xDeeKay

    @nverdier It has been changed, just needed a quick alternative for testing purposes.
    @unrealdesign I know it's not the best, but hey, I'm always learning. Thanks, I will look into this.
     
Thread Status:
Not open for further replies.

Share This Page