import 'dart:async'; typedef void OnTimerTickCallback(int millisUntilFinished); /* //示例代码:延时执行 timerUtils = TimerUtils(mDuration: 3000) ..startDelayTimer() ..setOnTimerTickCallback((millisUntilFinished) { print("执行定时任务了:$millisUntilFinished"); }); //示例代码:倒计时60秒 timerUtils = TimerUtils(mDuration: 1000,mTotalTime: 60 * 1000) ..startCountDown() ..setOnTimerTickCallback((millisUntilFinished) { print("执行定时任务了:$millisUntilFinished"); }); */ class TimerUtils { /// mDuration:间隔时间或延时时间 , 默认为1000毫秒 /// mTotalTime:倒计时的总时间 TimerUtils({this.mDuration = Duration.millisecondsPerSecond, this.mTotalTime = 0}); /// Timer. Timer? _mTimer; /// Timer是否启动. bool _isActive = false; /// Timer间隔 单位毫秒,默认1000毫秒(1秒). int mDuration; /// 倒计时总时间 int mTotalTime; //单位毫秒 /// 回调 OnTimerTickCallback? _onTimerTickCallback; /// 设置Timer间隔. void setInterval(int interval) { if (interval <= 0) interval = Duration.millisecondsPerSecond; mDuration = interval; } /// 设置倒计时总时间. void setTotalTime(int totalTime) { if (totalTime <= 0) return; mTotalTime = totalTime; } /// 启动延时任务 void startDelayTimer() { _mTimer = Timer(Duration(milliseconds: mDuration), () { _doCallback(0); }); } /// 启动定时任务的Timer.例如每隔1秒执行一次 void startPeriodicTimer() { if (_isActive || mDuration <= 0) return; _isActive = true; Duration duration = Duration(milliseconds: mDuration); _doCallback(0); _mTimer = Timer.periodic(duration, (Timer timer) { _doCallback(timer.tick); }); } /// 启动倒计时Timer. 每隔1秒执行一次,总共执行长时间 void startCountDown() { if (_isActive || mDuration <= 0 || mTotalTime <= 0) return; _isActive = true; Duration duration = Duration(milliseconds: mDuration); _doCallback(mTotalTime); _mTimer = Timer.periodic(duration, (Timer timer) { int time = mTotalTime - mDuration; mTotalTime = time; if (time >= mDuration) { _doCallback(time); } else if (time == 0) { _doCallback(time); cancel(); } else { timer.cancel(); Future.delayed(Duration(milliseconds: time), () { mTotalTime = 0; _doCallback(0); cancel(); }); } }); } void _doCallback(int time) { if (_onTimerTickCallback != null) { _onTimerTickCallback!(time); } } /// 重设倒计时总时间. void updateTotalTime(int totalTime) { cancel(); mTotalTime = totalTime; startCountDown(); } /// Timer是否启动. bool isActive() { return _isActive; } /// 取消计时器. void cancel() { if (_mTimer != null) { if (_mTimer!.isActive) { _mTimer?.cancel(); } _mTimer = null; } _isActive = false; } /// 设置Timer的监听 void setOnTimerTickCallback(OnTimerTickCallback callback) { _onTimerTickCallback = callback; } }