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 } 037 autoSave = null; 038 } 039 } 040 041 @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value="SLF4J_FORMAT_SHOULD_BE_CONST", 042 justification="I18N of Info Message") 043 private static void saveFiles() { 044 while (true) { 045 synchronized (autoSave) { 046 if (!Setup.isAutoSaveEnabled()) { 047 break; 048 } 049 try { 050 autoSave.wait(60000); // check every minute 051 } catch (InterruptedException e) { 052 break; // stop was called 053 } 054 if (OperationsXml.areFilesDirty()) { 055 log.debug("Detected dirty operation files"); 056 try { 057 autoSave.wait(60000); // wait another minute before 058 // saving 059 } catch (InterruptedException e) { 060 //do nothing 061 } 062 if (!Setup.isAutoSaveEnabled()) { 063 break; 064 } 065 if (InstanceManager.getDefault(TrainManager.class).isAnyTrainBuilding()) { 066 log.debug("Detected trains being built"); 067 continue; 068 } 069 if (OperationsXml.areFilesDirty()) { 070 OperationsXml.save(); 071 log.info(Bundle.getMessage("InfoFilesSaved")); 072 } 073 } 074 } 075 } 076 autoSave = null; // done 077 } 078 079 private final static Logger log = LoggerFactory.getLogger(AutoSave.class); 080}