1. import java.io.IOException;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.ScheduledExecutorService;
  4. import java.util.concurrent.TimeUnit;
  5. public class RecordBootstrapper {
  6. private final String userRecordScriptPath;
  7. private final long retryIntervalSeconds;
  8. private final int maxRetries;
  9. public RecordBootstrapper(String userRecordScriptPath, long retryIntervalSeconds, int maxRetries) {
  10. this.userRecordScriptPath = userRecordScriptPath;
  11. this.retryIntervalSeconds = retryIntervalSeconds;
  12. this.maxRetries = maxRetries;
  13. }
  14. public void startBootstrapping() {
  15. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  16. scheduler.scheduleAtFixedRate(this::bootstrapRecord, 0, retryIntervalSeconds, TimeUnit.SECONDS);
  17. // Handle potential shutdown gracefully (optional, but recommended)
  18. Runtime.getRuntime().addShutdownHook(new Thread(() -> {
  19. scheduler.shutdown();
  20. try {
  21. if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {
  22. scheduler.shutdownNow();
  23. }
  24. } catch (InterruptedException e) {
  25. scheduler.shutdownNow();
  26. Thread.currentThread().interrupt();
  27. }
  28. }));
  29. }
  30. private void bootstrapRecord() {
  31. try {
  32. executeScript(userRecordScriptPath);
  33. } catch (IOException e) {
  34. System.err.println("Error executing script: " + e.getMessage());
  35. // Retry logic
  36. if (getRemainingRetries() > 0) {
  37. System.out.println("Retrying in " + retryIntervalSeconds + " seconds...");
  38. } else {
  39. System.err.println("Max retries reached. Failed to execute script.");
  40. }
  41. }
  42. }
  43. private void executeScript(String scriptPath) throws IOException {
  44. // Simulate script execution (replace with actual script execution logic)
  45. System.out.println("Executing script: " + scriptPath);
  46. // Replace with your script execution logic (e.g., using ProcessBuilder)
  47. // Example:
  48. // Process process = Runtime.getRuntime().exec("java -jar " + scriptPath);
  49. // process.waitFor();
  50. }
  51. private int getRemainingRetries() {
  52. // Implement retry counter logic here (e.g., using a class variable or external storage)
  53. return maxRetries; // Placeholder - replace with actual retry counter
  54. }
  55. public static void main(String[] args) {
  56. // Example Usage
  57. String scriptPath = "/path/to/user_record_script.sh"; // Replace with your script path
  58. long retryInterval = 5; // Retry every 5 seconds
  59. int maxRetries = 3; // Maximum number of retries
  60. RecordBootstrapper bootstrapper = new RecordBootstrapper(scriptPath, retryInterval, maxRetries);
  61. bootstrapper.startBootstrapping();
  62. }
  63. }

Add your comment