Building Local Calendar Sync Day 06: Launch on Startup and run in the Background

At day 6 of building Local Calendar Sync, we make sure, the app Launches on Startup and runs the sync in the Background.

Building Local Calendar Sync Day 06: Launch on Startup and run in the Background

The core idea of the Local Calendar Sync application is, that it does all the work of creating blockers and syncing my calendar in the background. For this, we need to ensure, that the syncing algorithm runs repetitively on a schedule and that the app automatically starts up, even when the computer gets restarted.

Launch on Startup

Let's start with Launching on Startup. Most background app, offer the user to choose, whether they want to toggle auto-start or not. After reading some official documentation, I decided this was too complicated for such a simple task, so I decided to use the LaunchAtLogin 3rd party package, which also provides a UI Checkbox button, that I can add to the settings screen with a single line of code.

LaunchAtLogin.Toggle("Launch on startup")

Run in the Background

The app already starts silently in the Background. So all we need to add to ensure full background sync, is a timer, that executes the sync logic every 10 minutes or so (will be configurable via Settings later). The Timer class in Swift has a scheduledTimer function, which does exactly that.

// Run every 10 mins
var timer = Timer.scheduledTimer(withTimeInterval: 10 * 60, repeats: true, block: { _ in
    Task {
        do {
            try await CalendarService.shared.initAccess()
            await CalendarService.shared.sync()
        } catch {
            print("An error occurred while syncing the calendar")

I added the code above to the main LocalCalendarSyncApp class, which ensures that it gets executed on startup and ensures the sync logic gets executed every 10 minutes.

Aaaaaaaand with that, the first version of the app is done. 👏 I have spent 6 days on coding it. The last day will be about publishing it to the App Store. Stay tuned.

☝️ Advertisement Block: I will buy myself a pizza every time I make enough money with these ads to do so. So please feed a hungry developer and consider disabling your Ad Blocker.