1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Path;
  5. import java.nio.file.Paths;
  6. import java.time.Instant;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.ScheduledExecutorService;
  9. import java.util.concurrent.TimeUnit;
  10. public class TimestampProcessTeardown {
  11. private static final int CLEANUP_INTERVAL = 60; // seconds
  12. private static final int NUM_THREADS = 4;
  13. private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(NUM_THREADS);
  14. public static void main(String[] args) throws IOException {
  15. // Example usage: Create some test files with timestamps
  16. createTestFiles();
  17. // Schedule the cleanup task to run periodically
  18. scheduler.scheduleAtFixedRate(CleanupTask::run, 0, CLEANUP_INTERVAL, TimeUnit.SECONDS);
  19. // Keep the main thread alive to allow the scheduler to run.
  20. // In a real application, this could be replaced with a more appropriate
  21. // long-running task or service. For testing, we just keep it running.
  22. try {
  23. Thread.sleep(60 * 60 * 1000); // Run for an hour
  24. } catch (InterruptedException e) {
  25. Thread.currentThread().interrupt();
  26. } finally {
  27. scheduler.shutdown();
  28. }
  29. }
  30. static void createTestFiles() throws IOException{
  31. File testDir = new File("test_timestamps");
  32. if(!testDir.exists()){
  33. testDir.mkdir();
  34. }
  35. for(int i = 0; i < 10; i++){
  36. Path filePath = Paths.get("test_timestamps/file_" + i + ".txt");
  37. Files.writeString(filePath, "Timestamp: " + Instant.now());
  38. }
  39. }
  40. static class CleanupTask implements Runnable {
  41. @Override
  42. public void run() {
  43. try {
  44. File testDir = new File("test_timestamps");
  45. if (testDir.exists() && testDir.isDirectory()) {
  46. File[] files = testDir.listFiles();
  47. if (files != null) {
  48. for (File file : files) {
  49. if (file.isFile() && file.getName().matches("file_\\d+\\.txt")) {
  50. long lastModified = file.lastModified();
  51. if (System.currentTimeMillis() - lastModified > 60 * 60 * 24) { // Delete files older than 1 day
  52. try {
  53. Files.deleteIfExists(Paths.get(file.getAbsolutePath()));
  54. System.out.println("Deleted: " + file.getAbsolutePath());
  55. } catch (IOException e) {
  56. System.err.println("Error deleting " + file.getAbsolutePath() + ": " + e.getMessage());
  57. }
  58. }
  59. }
  60. }
  61. }
  62. }
  63. } catch (IOException e) {
  64. System.err.println("Error during cleanup: " + e.getMessage());
  65. }
  66. }
  67. }
  68. }

Add your comment