我正在编写一个命令行工具,想要处理各种输入,并且还希望在特定命令上触发Timer()并在另一个命令上停止它。 不幸的是,这不起作用
import Foundation
class timerTest : NSObject {
var myTimer : Timer? = nil
func startTimer() {
myTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {_ in
print("Hello")
})
let runLoop = RunLoop()
runLoop.add(myTimer!, forMode: .defaultRunLoopMode)
RunLoop.current.run()
}
func stopTimer() {
myTimer?.invalidate()
}
}
var a = timerTest()
print("Ready")
while true {
var keyboard = FileHandle.standardInput
var inputData = keyboard.availableData
var string = NSString(data: inputData, encoding:String.Encoding.utf8.rawValue) as! String
string = string.trimmingCharacters(in: .whitespacesAndNewlines)
if string == "timer" { a.startTimer() }
if string == "stop" { a.stopTimer() }
}
答案 0 :(得分:1)
您可以使用以下内容:
import Foundation
var shouldKeepRunning = true
class CLIInput:NSObject {
var inputTimer:Timer? = nil
var myTimer:Timer? = nil
func getInput() {
inputTimer = Timer.scheduledTimer(withTimeInterval:1, repeats:false, block: {_ in
var input = readLine()!
input = input.trimmingCharacters(in: .whitespacesAndNewlines)
print("Input: \(input)")
if input == "timer" {
print("Start timer")
self.myTimer = Timer.scheduledTimer(withTimeInterval:1, repeats: true, block: {_ in
print("Hello")
})
}
if input == "stop" {
print("Stop timer")
self.myTimer?.invalidate()
self.myTimer = nil
}
if input == "exit" {
print("Time to exit")
self.inputTimer?.invalidate()
self.inputTimer = nil
shouldKeepRunning = false
return
}
// Otherwise, set up timer again
self.getInput()
})
}
}
print("Start")
var cli = CLIInput()
cli.getInput()
let theRL = RunLoop.current
while shouldKeepRunning && theRL.run(mode: .defaultRunLoopMode, before: .distantFuture) { }
但是,无论何时等待标准输入的输入,您都会发现定时器模块输出没有显示,因为输出被阻止直到输入完成。只要你的计时器进程不需要做任何输出,上面可能(或可能不是,取决于你的要求)工作......