Advertisement
osx11

bukkit async example, generated by chatgpt

Mar 22nd, 2023 (edited)
550
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. public class MyPlugin extends JavaPlugin {
  2.  
  3.     private Connection dbConnection;
  4.  
  5.     @Override
  6.     public void onEnable() {
  7.         // Set up database connection
  8.         try {
  9.             dbConnection = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
  10.         } catch (SQLException e) {
  11.             e.printStackTrace();
  12.         }
  13.  
  14.         // Schedule a task to run asynchronously after a delay of 20 ticks (1 second)
  15.         new BukkitRunnable() {
  16.             @Override
  17.             public void run() {
  18.                 // Code to run asynchronously
  19.                 try {
  20.                     // Load data from database using separate thread
  21.                     CompletableFuture.supplyAsync(() -> loadDataFromDatabase())
  22.                             .thenAccept(data -> {
  23.                                 // Code to run on main game thread after data has been loaded
  24.                                 Bukkit.broadcastMessage("Loaded data from database: " + data);
  25.                             })
  26.                             .exceptionally(ex -> {
  27.                                 // Code to run if an exception occurs while loading data
  28.                                 getLogger().severe("Error loading data from database: " + ex.getMessage());
  29.                                 return null;
  30.                             }).join();
  31.                 } catch (Exception ex) {
  32.                     getLogger().severe("Error scheduling async task: " + ex.getMessage());
  33.                 }
  34.             }
  35.         }.runTaskLaterAsynchronously(this, 20);
  36.     }
  37.  
  38.     private List<String> loadDataFromDatabase() {
  39.         List<String> data = new ArrayList<>();
  40.         try (Statement statement = dbConnection.createStatement();
  41.              ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable")) {
  42.             while (resultSet.next()) {
  43.                 data.add(resultSet.getString("column_name"));
  44.             }
  45.         } catch (SQLException e) {
  46.             e.printStackTrace();
  47.         }
  48.         return data;
  49.     }
  50.  
  51.     @Override
  52.     public void onDisable() {
  53.         // Close database connection
  54.         try {
  55.             dbConnection.close();
  56.         } catch (SQLException e) {
  57.             e.printStackTrace();
  58.         }
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement