Mohammad Eslami
Mohammad Eslami

Reputation: 544

How set timeout for my long running time function?

I have a function with some codes that maybe takes long time to complete. I want the function stopped from continuing if it takes time more than a specific time. How can I implement this? I tried below solution but it doesn't stop the execution.

override func viewDidLoad() {
    super.viewDidLoad()
    let task = DispatchWorkItem {
    self.myfunction()
    }


    DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {
        task.cancel()
    })
    task.perform()
}

func myfunction() -> Void {
    /*some codes that may take long time to complete*/
}

Upvotes: 3

Views: 2548

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Try this

 var stop:Bool!
 override func viewDidLoad() {
  super.viewDidLoad()

   stop = false
   let task = DispatchWorkItem {
   self.myfunction()
  }


   DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {
        stop = true
    })
     task.perform()
  }

func myfunction() -> Void {

   if(stop)
   {

      // invalidate timer , break for loop or return

   }


 }

// better approach for web services to set time out in request here set request to 5 seconds timeout

  let urlRequest = NSMutableURLRequest(url: newUrl! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)

        let queue = OperationQueue()

        NSURLConnection.sendAsynchronousRequest(urlRequest as URLRequest, queue: queue)
        {

         }

Upvotes: 2

Related Questions