Heavy code

Discussion in 'Plugin Development' started by Welite, Jan 8, 2014.

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

    Welite

    Hi, I have written a plugin that counts players and their nicks and send this data to DB, but when it runs server has lag, but I dont know why, because I think that this code is not heavy at all, can someone tell me if I have something wrong or why is my server lagging when this loop starts ?




    Full code:
    Code:
    public class Pocitadlo extends JavaPlugin {
     
        public void onEnable() {
            Timer timer = new Timer();
            TimerTask tt = new TimerTask(){
                public void run(){
                    String hostname = getConfig().getString("MySQL.hostname");
                    String user = getConfig().getString("MySQL.user");
                    String pass = getConfig().getString("MySQL.password");
                   
                    String fulllist = "";
                    int i = 0;
                    for(Player hrac : Bukkit.getOnlinePlayers()) {
                       
                        if (i == 0) { fulllist = fulllist + hrac.getName(); }
                        if (i > 0) { fulllist = fulllist + ", " + hrac.getName(); }
                        i++;
                    }
                    try{
                        Connection con = DriverManager.getConnection(hostname, user, pass);
                        PreparedStatement rs = con.prepareStatement("update " + "status" + " set data = '"+i+"'  where informace = '"+"online"+"'");
                        PreparedStatement rs2 = con.prepareStatement("update " + "status" + " set data = '"+fulllist+"'  where informace = '"+"playerlist"+"'");
                        int rs_done = rs.executeUpdate();
                        int rs_done2 = rs2.executeUpdate();
                        con.close();
                        }
                        catch(Exception ecc){           
                        System.out.println(ecc.toString());             
                        }
                }
                };
                timer.schedule(tt, 1000, 1000*30);
        }
       
        public void onDisable() {}
    }
     
  2. Offline

    Forseth11

    Connection could be causing the lag when trying to make the connection.
     
  3. Offline

    _Filip

    Save it using an other thread.
     
  4. Using another thread when actually connecting and submitting the data to the database is a good idea but you might also just keep the connection from the start and just open it on enable.
     
Thread Status:
Not open for further replies.

Share This Page