This repository was archived by the owner on Apr 30, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTableCleanupTask.java
More file actions
65 lines (56 loc) · 2.56 KB
/
TableCleanupTask.java
File metadata and controls
65 lines (56 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import com.mysql.cj.xdevapi.PreparableStatement;
public class TableCleanupTask extends Thread {
private static final String URL = "jdbc:mysql://localhost:3306/ticket_booking_db";
private static final String USER = "root";
private static final String PASSWORD = "";
@Override
public void run() {
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
while (true) {
try (Statement statement = connection.createStatement()) {
// Query to find trips that have ended
String query = "SELECT TripID FROM Trip WHERE StartTime < NOW()";
try (ResultSet resultSet = statement.executeQuery(query)) {
while (resultSet.next()) {
int tripID = resultSet.getInt("TripID");
String tableName = "tripseat_" + tripID;
// Call the synchronized method to delete the table
deleteTable(connection, tableName);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
// Sleep for a while before checking again
try {
Thread.sleep(60000); // Sleep for 1 minute
} catch (InterruptedException e) {
e.printStackTrace();
break; // Exit the loop if interrupted
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// Synchronized method to delete a table
private synchronized void deleteTable(Connection connection, String tableName) {
try (Statement statement = connection.createStatement()) {
String deleteTableQuery = "DROP TABLE IF EXISTS " + tableName;
int rowsAffected = statement.executeUpdate(deleteTableQuery);
if (rowsAffected == 0) {
// No rows were affected, which means the table did not exist or was already deleted
} else {
// Rows were affected, which means the table was successfully deleted
// System.out.println("Successfully deleted table: " + tableName);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}