Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
How to run code at a specific time in swift

I've looked all over but I can't find an answer to this question. I want a specific function to run at 6:00 am and 6:00 pm every day for a day/night mode in my app. This doesn't need to run in the background, just when the app is open, but I also want to prefom other functions of the app as well while it checks for the time.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do it like this. Just set a Date with the Calendar object. Put your specific time in military hours (from 0 to 24, with 0 being midnight) and Voila!, if your app is in the foreground and the specified time kicks in, you will see the function you used as the selector execute

Give it a shot and happy coding

override func viewDidLoad() {
    super.viewDidLoad()

    let calendar = Calendar.current 

    let now = Date()
    let date = calendar.date(
        bySettingHour: 23,
        minute: 52,
        second: 0,
        of: now)!

    let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)

    RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
}

func runCode() {
    print("Do whatever here")
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!