import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TimestampProcessTeardown {
private static final int CLEANUP_INTERVAL = 60; // seconds
private static final int NUM_THREADS = 4;
private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(NUM_THREADS);
public static void main(String[] args) throws IOException {
// Example usage: Create some test files with timestamps
createTestFiles();
// Schedule the cleanup task to run periodically
scheduler.scheduleAtFixedRate(CleanupTask::run, 0, CLEANUP_INTERVAL, TimeUnit.SECONDS);
// Keep the main thread alive to allow the scheduler to run.
// In a real application, this could be replaced with a more appropriate
// long-running task or service. For testing, we just keep it running.
try {
Thread.sleep(60 * 60 * 1000); // Run for an hour
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
scheduler.shutdown();
}
}
static void createTestFiles() throws IOException{
File testDir = new File("test_timestamps");
if(!testDir.exists()){
testDir.mkdir();
}
for(int i = 0; i < 10; i++){
Path filePath = Paths.get("test_timestamps/file_" + i + ".txt");
Files.writeString(filePath, "Timestamp: " + Instant.now());
}
}
static class CleanupTask implements Runnable {
@Override
public void run() {
try {
File testDir = new File("test_timestamps");
if (testDir.exists() && testDir.isDirectory()) {
File[] files = testDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().matches("file_\\d+\\.txt")) {
long lastModified = file.lastModified();
if (System.currentTimeMillis() - lastModified > 60 * 60 * 24) { // Delete files older than 1 day
try {
Files.deleteIfExists(Paths.get(file.getAbsolutePath()));
System.out.println("Deleted: " + file.getAbsolutePath());
} catch (IOException e) {
System.err.println("Error deleting " + file.getAbsolutePath() + ": " + e.getMessage());
}
}
}
}
}
}
} catch (IOException e) {
System.err.println("Error during cleanup: " + e.getMessage());
}
}
}
}
Add your comment