Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Created October 29, 2017 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dedeexe/cff412d4f4c975174184fa7fbaeeb5cd to your computer and use it in GitHub Desktop.
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.
//
// 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