55import com .google .gson .JsonElement ;
66import com .google .gson .JsonObject ;
77import com .google .gson .JsonPrimitive ;
8- import com .hypixel .hytale .server .core .HytaleServer ;
98import com .hypixel .hytale .server .core .util .BsonUtil ;
109import io .github .syst3ms .skriptparser .config .Config .ConfigSection ;
1110import io .github .syst3ms .skriptparser .log .ErrorType ;
4039import java .nio .file .Files ;
4140import java .nio .file .Path ;
4241import java .util .Locale ;
43- import java .util .concurrent .ScheduledFuture ;
4442import java .util .concurrent .TimeUnit ;
4543import java .util .concurrent .atomic .AtomicBoolean ;
4644import java .util .concurrent .atomic .AtomicInteger ;
@@ -60,7 +58,7 @@ public enum Type {
6058 private BsonDocument bsonDocument ;
6159 private final AtomicInteger changes = new AtomicInteger (0 );
6260 private final int changesToSave = 500 ;
63- ScheduledFuture <?> schedule ;
61+ private Thread saveThread ;
6462
6563 public JsonVariableStorage (SkriptLogger logger , String name ) {
6664 super (logger , name );
@@ -92,17 +90,32 @@ protected void allLoaded() {
9290 }
9391
9492 private void startFileWatcher () {
95- this .schedule = HytaleServer .SCHEDULED_EXECUTOR .scheduleAtFixedRate (() -> {
96- if (this .changes .get () >= this .changesToSave ) {
97- try {
98- saveVariables (false );
99- this .changes .set (0 );
100- } catch (IOException e ) {
101- Utils .error ("Failed to save variable file" , ErrorType .EXCEPTION );
102- throw new RuntimeException (e );
93+ this .saveThread = new Thread ( () -> {
94+ try {
95+ while (!Thread .currentThread ().isInterrupted ()) {
96+ // Sleep for 5 minutes
97+ TimeUnit .MINUTES .sleep (5 );
98+
99+ // Start checking for variables to save
100+ if (this .changes .get () >= this .changesToSave ) {
101+ try {
102+ saveVariables (false );
103+ this .changes .set (0 );
104+ } catch (IOException e ) {
105+ Utils .error ("Failed to save variable file" , ErrorType .EXCEPTION );
106+ throw new RuntimeException (e );
107+ }
108+ }
103109 }
110+ } catch (InterruptedException e ) {
111+ // Restore interrupt status and exit
112+ Thread .currentThread ().interrupt ();
113+ Utils .error ("Variable Save Thread was interrupted, stopping..." );
104114 }
105- }, 5 , 5 , TimeUnit .MINUTES );
115+
116+ },"HySkript-Variable-Save-Thread" );
117+ this .saveThread .setDaemon (true );
118+ this .saveThread .start ();
106119 }
107120
108121 private void loadVariablesFromFile () {
@@ -251,7 +264,7 @@ public void close() throws IOException {
251264
252265 private void saveVariables (boolean finalSave ) throws IOException {
253266 if (finalSave ) {
254- this .schedule . cancel ( true );
267+ this .saveThread . interrupt ( );
255268 }
256269 try {
257270 Variables .getLock ().lock ();
0 commit comments