You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为指定POST请求代码实现带15秒休眠的无限循环后台线程

How to Run Your POST Request in a Background Infinite Loop with 15-Second Delay

Got it, let's get this sorted for you! Here's a clean, safe way to wrap your POST request in a background thread that runs infinitely, waiting 15 seconds between each request:

Key Notes Before the Code:

  • We’ll use a background dispatch queue to avoid blocking your app’s main thread (critical for keeping your UI responsive).
  • Added optional binding for the URL to prevent crashes if your URL string is invalid (never force-unwrap with ! unless you’re 100% sure it’s safe!).
  • Included a controllable loop flag (instead of a raw while true) so you can stop the loop later if needed—just set shouldKeepRunning = false from any thread when you’re done.

Full Implementation

// Thread-safe flag to control the loop (optional but highly recommended)
var shouldKeepRunning = true

// Launch the background thread
DispatchQueue.global(qos: .background).async {
    while self.shouldKeepRunning {
        // 1. Set up your POST request
        guard let url = URL(string: "my url string") else {
            print("Invalid URL provided")
            // Wait 15 seconds before trying again
            Thread.sleep(forTimeInterval: 15)
            continue
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        let postString = "my post string"
        request.httpBody = postString.data(using: .utf8)
        
        // 2. Execute the request
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Request failed with error: \(error.localizedDescription)")
                return
            }
            
            guard let responseData = data else {
                print("No data received from server")
                return
            }
            
            if let responseString = String(data: responseData, encoding: .utf8) {
                print("Server response: \(responseString)")
            } else {
                print("Failed to parse response data as UTF-8 string")
            }
        }
        task.resume()
        
        // 3. Wait 15 seconds before the next loop iteration
        Thread.sleep(forTimeInterval: 15)
    }
}

// To stop the loop later (e.g., when the app goes to background):
// shouldKeepRunning = false

Important Considerations:

  • Thread Safety: Boolean assignments are atomic in Swift, so updating shouldKeepRunning from the main thread is safe here. For more complex state, you might want to use a DispatchSemaphore or NSLock.
  • Background Execution: If your app enters the background, iOS might suspend this thread. If you need to run requests indefinitely in the background, you’ll need to implement Apple’s official background task APIs (check Apple’s docs for background execution guidelines).
  • Error Handling: The code includes basic error handling for invalid URLs, request failures, and missing data—feel free to expand this based on your app’s specific needs.

内容的提问来源于stack exchange,提问作者Francesco Gregori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:20:26