Created
October 29, 2017 21:49
-
-
Save dedeexe/cff412d4f4c975174184fa7fbaeeb5cd to your computer and use it in GitHub Desktop.
Schedule to execute an action after a delay. If a new execution is scheduled before the old one be executed, it will override the old and a new delay is set.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Trigger.swift | |
// | |
// Created by dede.exe on 15/10/17. | |
// Copyright © 2017 dede.exe. All rights reserved. | |
// | |
import Foundation | |
public class Trigger { | |
public let action : (()->Void)? | |
public let interval : TimeInterval | |
private var timer : Timer? | |
init() { | |
interval = 0 | |
action = nil | |
} | |
init(in interval:TimeInterval, action:(()->Void)? = nil) { | |
self.interval = interval | |
self.action = action | |
} | |
func execute() { | |
self.timer?.invalidate() | |
self.timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(actionTriggered), userInfo: nil, repeats: false) | |
} | |
@objc private func actionTriggered(sender:Timer) { | |
action?() | |
sender.invalidate() | |
} | |
deinit { | |
timer?.invalidate() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment