package com.example.chemical.utils

import android.os.Handler
import android.os.Looper

class HandlerUtil  private constructor() {
    private val handler = Handler(Looper.getMainLooper())
    private var isRunning = false

    companion object {
        private var instance: HandlerUtil? = null

        fun getInstance(): HandlerUtil {
            if (instance == null) {
                instance = HandlerUtil()
            }
            return instance!!
        }
    }

    fun startTask(task: Runnable, intervalMillis: Long) {
        isRunning = true
        handler.postDelayed(object : Runnable {
            override fun run() {
                if (isRunning) {
                    task.run()
                    handler.postDelayed(this, intervalMillis)
                }
            }
        }, intervalMillis)
    }

    fun stopAllTasks() {
        isRunning = false
        handler.removeCallbacksAndMessages(null)
    }
    fun removeCallbacks(task: Runnable) {
        isRunning = false
        handler.removeCallbacks(task)
    }
}