Created
February 7, 2021 11:04
-
-
Save gepron1x/73c1faec3a02d00483fc874ba4a19702 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import net.md_5.bungee.api.ProxyServer; | |
import net.md_5.bungee.api.plugin.Plugin; | |
import net.md_5.bungee.api.scheduler.TaskScheduler; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
import java.util.function.Consumer; | |
public class AsyncSQLWorker { | |
private Connection connection; | |
private final Plugin owner; | |
private final String host, username, password, database; | |
private static final TaskScheduler scheduler = ProxyServer.getInstance().getScheduler(); | |
public AsyncSQLWorker(final Plugin owner, | |
final String host, | |
final String username, | |
final String password, | |
final String database) { | |
this.host = host; | |
this.username = username; | |
this.password = password; | |
this.database = database; | |
this.owner = owner; | |
} | |
public void connect(final Consumer<Connection> onConnect) { | |
scheduler.runAsync(owner, () -> { | |
try { | |
connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database, username, password); | |
onConnect.accept(connection); | |
} catch (SQLException throwables) { | |
throwables.printStackTrace(); | |
} | |
}); | |
} | |
public void executeAsync(final Consumer<Connection> task) { | |
scheduler.runAsync(owner, () -> | |
task.accept(connection) | |
); | |
} | |
public void closeConnection() { | |
scheduler.runAsync(owner, () -> { | |
if(null != connection) { | |
try { | |
connection.close(); | |
} catch (SQLException throwables) { | |
throwables.printStackTrace(); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment