从计时器内调用异步函数

问题描述 投票:0回答:2

我有一个异步函数,必须在计时器内的每个给定时间调用它。 为了避免 Xcode 错误,

func firetimer()  {
      
         let newtimer = Timer(timeInterval: 1.0, repeats: true) { newtimer in
            self.myAsyncFunction() // 'async' call in a function that does not support concurrency
        }
        RunLoop.current.add(newtimer, forMode: .common)
    }

我尝试将其放入任务中,但这在运行时出现“Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)”错误。

func firetimer()  {
      
         let newtimer = Timer(timeInterval: 1.0, repeats: true) { newtimer in
             Task{
            await self.myAsyncFunction() // not working
             }
        }
        RunLoop.current.add(newtimer, forMode: .common)
    }

事实上我不需要任何等待,下一次出现的函数可以在后者仍在工作时调用。 有什么提示可以做什么吗? 谢谢!

swift concurrency timer task runloop
2个回答
4
投票

尝试创建一个支持功能:

  1. 支持功能是同步的,但异步调用
    myAsyncFunction
func mySyncFunction() {

    // Call the asynchronous function
    Task {
        await self.myAsyncFunction()
    }
}
  1. fireTimer
  2. 调用支持功能
func fireTimer()  {
      
         let newTimer = Timer(timeInterval: 1.0, repeats: true) { newTimer in
            self.mySyncFunction()    // Synchronous
        }
        RunLoop.current.add(newTimer, forMode: .common)
    }
}

0
投票
    func connect() async -> CocoaMQTTConnAck {
        await withCheckedContinuation { continuation in
            connect { connAck in
                continuation.resume(returning: connAck)
            }
        }
    }

    func connect(completion: @escaping (CocoaMQTTConnAck) -> Void) {
        let clientID = "FindMySync-" + String(ProcessInfo().processIdentifier)

        mqttClient = CocoaMQTT(clientID: clientID, host: mqttConfiguration.host, port: mqttConfiguration.port)

        if let client = mqttClient {
            client.username = mqttConfiguration.user
            client.password = mqttConfiguration.password
            client.enableSSL = mqttConfiguration.ssl
            client.didConnectAck = { client, connAck in
                completion(connAck)
                return
            }
            let _ = client.connect()
        }
    }

let connAck = await connect()
© www.soinside.com 2019 - 2024. All rights reserved.