001package jmri.jmrit.operations.setup; 002 003import org.slf4j.Logger; 004import org.slf4j.LoggerFactory; 005 006import jmri.InstanceManager; 007import jmri.jmrit.operations.OperationsXml; 008import jmri.jmrit.operations.trains.TrainManager; 009 010/** 011 * Auto Save. When enabled will automatically save operation files. 012 * 013 * @author Daniel Boudreau Copyright (C) 2012 014 */ 015public class AutoSave { 016 017 static Thread autoSave = null; 018 019 public static synchronized void start() { 020 if (Setup.isAutoSaveEnabled() && autoSave == null) { 021 autoSave = jmri.util.ThreadingUtil.newThread(() -> { 022 saveFiles(); 023 }); 024 autoSave.setName("Operations Auto Save"); // NOI18N 025 autoSave.start(); 026 } 027 } 028 029 public static synchronized void stop() { 030 if (autoSave != null) { 031 autoSave.interrupt(); 032 try { 033 autoSave.join(); 034 } catch (InterruptedException e) { 035 // Do nothing 036 } catch (NullPointerException e) { 037 // Do nothing 038 } 039 autoSave = null; 040 } 041 } 042 043 @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value="SLF4J_FORMAT_SHOULD_BE_CONST", 044 justification="I18N of Info Message") 045 private static void saveFiles() { 046 while (true) { 047 synchronized (autoSave) { 048 if (!Setup.isAutoSaveEnabled()) { 049 break; 050 } 051 try { 052 autoSave.wait(60000); // check every minute 053 } catch (InterruptedException e) { 054 break; // stop was called 055 } 056 if (OperationsXml.areFilesDirty()) { 057 log.debug("Detected dirty operation files"); 058 try { 059 autoSave.wait(60000); // wait another minute before 060 // saving 061 } catch (InterruptedException e) { 062 //do nothing 063 } 064 if (!Setup.isAutoSaveEnabled()) { 065 break; 066 } 067 if (InstanceManager.getDefault(TrainManager.class).isAnyTrainBuilding()) { 068 log.debug("Detected trains being built"); 069 continue; 070 } 071 if (OperationsXml.areFilesDirty()) { 072 OperationsXml.save(); 073 log.info(Bundle.getMessage("InfoFilesSaved")); 074 } 075 } 076 } 077 } 078 autoSave = null; // done 079 } 080 081 private final static Logger log = LoggerFactory.getLogger(AutoSave.class); 082}