├── .gitignore
├── .github
├── workflows
│ ├── Build.yml
│ └── PublishDoc.yml
├── pull_request_template.md
├── CODE_OF_CONDUCT.md
└── CONTRIBUTING.md
├── .swiftpm
└── xcode
│ └── package.xcworkspace
│ └── xcshareddata
│ └── IDETemplateMacros.plist
├── WorkManager.podspec
├── Package.swift
├── LICENSE
├── Tests
└── WorkManagerTests
│ └── WorkManagerTests.swift
├── Sources
└── WorkManager
│ ├── Documentation.docc
│ └── WorkManager.md
│ └── WorkManager.swift
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /.build
3 | /Packages
4 | /*.xcodeproj
5 | xcuserdata/
6 | DerivedData/
7 | Package.resolved
8 | .swiftpm/config/registries.json
9 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
10 | .netrc
11 |
--------------------------------------------------------------------------------
/.github/workflows/Build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | pull_request:
7 | branches: [ "main" ]
8 |
9 | jobs:
10 | build:
11 | name: Build
12 | runs-on: macos-12
13 | steps:
14 | - uses: actions/checkout@v3
15 | - name: Build
16 | run: swift build -v
17 | - name: Run tests
18 | run: swift test -v
19 |
--------------------------------------------------------------------------------
/.swiftpm/xcode/package.xcworkspace/xcshareddata/IDETemplateMacros.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | FILEHEADER
6 | Create by ___FULLUSERNAME___ on ___DATE___
7 | //
8 | // ___FILENAME___
9 | // WorkManager
10 | //
11 | // Using Swift ___DEFAULTTOOLCHAINSWIFTVERSION___
12 | // Copyright © ___YEAR___ PT GoJek Indonesia. All rights reserved.
13 | // Licensed under Apache License v2.0
14 | //
15 |
16 |
17 |
--------------------------------------------------------------------------------
/WorkManager.podspec:
--------------------------------------------------------------------------------
1 | Pod::Spec.new do |s|
2 | s.name = "WorkManager"
3 | s.version = "0.10.0"
4 | s.summary = "WorkManager is a periodic task scheduler "
5 | s.description = "WorkMaanger shedules periodic task that get executed regardless of the app sessions"
6 |
7 | s.homepage = 'https://github.com/gojek/WorkManager'
8 | s.license = { :type => 'MIT', :file => 'LICENSE' }
9 |
10 | s.author = "Gojek"
11 | s.source = { :git => "https://github.com/gojek/WorkManager.git", :tag => "#{s.version}" }
12 |
13 | s.platform = :ios
14 | s.ios.deployment_target = '11.0'
15 | s.swift_version = '5.0'
16 |
17 | s.source_files = 'Sources/WorkManager/*.swift'
18 |
19 | end
20 |
--------------------------------------------------------------------------------
/Package.swift:
--------------------------------------------------------------------------------
1 | // swift-tools-version: 5.7
2 |
3 | import PackageDescription
4 |
5 | let package = Package(
6 | name: "WorkManager",
7 | platforms: [.iOS(.v12),
8 | .macOS(.v12),
9 | .watchOS(.v4),
10 | .tvOS(.v11)],
11 | products: [
12 | .library(
13 | name: "WorkManager",
14 | targets: ["WorkManager"]),
15 | ],
16 | dependencies: [
17 | .package(url: "https://github.com/apple/swift-docc-plugin.git", from: "1.0.0"),
18 | ],
19 | targets: [
20 | .target(
21 | name: "WorkManager",
22 | dependencies: []),
23 | .testTarget(
24 | name: "WorkManagerTests",
25 | dependencies: ["WorkManager"]),
26 | ]
27 | )
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 GO-JEK Tech
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ## Description
2 |
3 | A clear and concise description of the changes proposed in the pull request.
4 |
5 | ## Motivation and Context
6 |
7 | Why is this change required? What problem does it solve?
8 |
9 | ## How Has This Been Tested?
10 |
11 | Please describe the tests that you ran to verify your changes.
12 |
13 | ## Screenshots (if appropriate)
14 |
15 | If applicable, add screenshots to help explain your changes.
16 |
17 | ## Types of changes
18 |
19 | What types of changes does your code introduce to the library?
20 |
21 | - [ ] Bug fix (non-breaking change which fixes an issue)
22 | - [ ] New feature (non-breaking change which adds functionality)
23 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
24 |
25 | ## Checklist
26 |
27 | - [ ] I have performed a self-review of my own code
28 | - [ ] I have commented my code, particularly in hard-to-understand areas
29 | - [ ] I have made corresponding changes to the documentation
30 | - [ ] My changes generate no new warnings
31 | - [ ] I have added tests that prove my fix is effective or that my feature works
32 | - [ ] New and existing unit tests pass locally with my changes
33 |
--------------------------------------------------------------------------------
/Tests/WorkManagerTests/WorkManagerTests.swift:
--------------------------------------------------------------------------------
1 | import XCTest
2 | @testable import WorkManager
3 |
4 | final class WorkManagerTests: XCTestCase {
5 | let sut = WorkManager.shared
6 |
7 | func testQueuing() throws {
8 | let performExpectation = XCTestExpectation(description: "performExpectation")
9 | var didPerformed = false
10 | sut.enqueueUniquePeriodicWork(id: "com.example.task.one", interval: 20) {
11 | didPerformed = true
12 | performExpectation.fulfill()
13 | }
14 | wait(for: [performExpectation], timeout: 21)
15 | assert(didPerformed)
16 | }
17 |
18 | func testCancellation() throws {
19 | let performExpectation = XCTestExpectation(description: "performExpectation")
20 | var didPerformed = false
21 | sut.enqueueUniquePeriodicWork(id: "com.example.task.two", interval: 20) {
22 | didPerformed = true
23 | performExpectation.fulfill()
24 | }
25 | sleep(5)
26 | sut.cancelQueuedPeriodicWork(withId: "com.example.task.two")
27 | performExpectation.fulfill()
28 | wait(for: [performExpectation], timeout: 21)
29 | assert(!didPerformed)
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/.github/workflows/PublishDoc.yml:
--------------------------------------------------------------------------------
1 | name: PublishDocs
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 |
8 | pull_request:
9 | branches:
10 | - main
11 |
12 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
13 | permissions:
14 | contents: read
15 | pages: write
16 | id-token: write
17 |
18 | # Allow one concurrent deployment
19 | concurrency:
20 | group: "pages"
21 | cancel-in-progress: true
22 |
23 | jobs:
24 | docs:
25 | runs-on: macos-12
26 |
27 | steps:
28 | - uses: actions/checkout@v3
29 | - name: Set up Pages
30 | uses: actions/configure-pages@v1
31 | - name: Generate Docs Using Docc plugin
32 | run: |
33 | swift package --allow-writing-to-directory ./public \
34 | generate-documentation --target WorkManager \
35 | --disable-indexing \
36 | --transform-for-static-hosting \
37 | --hosting-base-path WorkManager \
38 | --output-path ./public
39 | - name: Upload artifact
40 | uses: actions/upload-pages-artifact@v1
41 | with:
42 | path: ./public
43 |
44 | deploy:
45 | environment:
46 | name: github-pages
47 | url: ${{ steps.deployment.outputs.page_url }}
48 | runs-on: ubuntu-latest
49 | needs: docs
50 |
51 | steps:
52 | - name: Deploy Docs
53 | uses: actions/deploy-pages@v1
54 |
--------------------------------------------------------------------------------
/Sources/WorkManager/Documentation.docc/WorkManager.md:
--------------------------------------------------------------------------------
1 | # ``WorkManager``
2 |
3 | WorkManager is a task scheduler, it allows apps to schedule periodic tasks to perform in certain intervals
4 | of duration, while persisting the tasks throughout app launches, and termination cycles.
5 |
6 | WorkManager uses UserDeafult to store the last run time and the interval every time the app comes to the
7 | foreground your app passes control to WorkManager to let it evaluate and run if the task needed to be run
8 | again.
9 |
10 | ## Usage
11 |
12 | ### Enqueuing task
13 |
14 | WorkManager needs you to register a closure with a unique task id, preferably during the app launch sequence, suggested place would be before returning from `application(_:, didFinishLaunchingWithOptions:) -> Bool`.
15 |
16 | ```swift
17 | import WorkManager
18 |
19 | // Scheduling to perform in every 2 days
20 | WorkManager.shared.enqueueUniquePeriodicWork(id: "com.unique.task.id", interval: 2 * 24 * 60 * 60) {
21 | cleanUpDisk()
22 | }
23 | ```
24 |
25 | ### Cancelling Task
26 |
27 | In case you want to cancel a scheduled task on the fly you could pass the unique id of the task to WorkManager and call cancel
28 |
29 | ```swift
30 | WorkManager.shared.cancelQueuedPeriodicWork(withId: "com.unique.task.id")
31 | ```
32 |
33 | WorkManager As of now only performs the tasks in the foreground, it will evaluate every launch time if the time interval has passed against the last run time, which is a response to which it will perform your registered closure.
34 |
35 | ## Topics
36 |
37 | ### Types
38 |
39 | - ``WorkManager/WorkManager/Task``
40 |
--------------------------------------------------------------------------------
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behaviour that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behaviour by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behaviour and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behaviour.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviours that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behaviour may be reported by contacting the project team at devx@gojek.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
48 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WorkManager
2 |
3 | [](https://github.com/apple/swift-package-manager) [](https://github.com/gojekfarm/WorkManager/actions/workflows/Build.yml) [](http://cocoadocs.org/docsets/WorkManager)
4 |
5 | WorkManager is a task scheduler, it allows apps to schedule periodic tasks to perform in certain intervals of duration, while persisting the tasks throughout app launches, and termination cycles.
6 |
7 | WorkManager uses UserDeafult to store the last run time and the interval every time the app comes to the foreground your app passes control to WorkManager to let it evaluate and run if the task needed to be run again.
8 |
9 | ## Installation
10 |
11 | ### Swift Package Manager
12 |
13 | The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into `swift`.
14 | To add a package dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter below repository URL
15 |
16 | ```
17 | https://github.com/gojek/WorkManager.git
18 | ```
19 |
20 |
21 | Once you have your Swift package set up, adding WorkManager as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
22 |
23 | ```swift
24 | dependencies: [
25 | .package(url: "https://github.com/gojek/WorkManager.git", .upToNextMajor(from: "0.10.0"))
26 | ]
27 | ```
28 |
29 | ### Cocoapods
30 |
31 | [CocoaPods](https://cocoapods.org/) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate WorkManager into your Xcode project using CocoaPods, specify the following pod in your Podfile:
32 |
33 | ```ruby
34 | pod 'WorkManager'
35 | ```
36 |
37 | ## Usage
38 |
39 | ### Enqueuing task
40 |
41 | WorkManager needs you to register a closure with a unique task id, preferably during the app launch sequence, suggested place would be before returning from `application(_:, didFinishLaunchingWithOptions:) -> Bool`.
42 |
43 | ```swift
44 | import WorkManager
45 |
46 | // Scheduling to perform in every 2 days
47 | WorkManager.shared.enqueueUniquePeriodicWork(id: "com.unique.task.id", interval: 2 * 24 * 60 * 60) {
48 | cleanUpDisk()
49 | }
50 | ```
51 |
52 | ### Cancelling Task
53 |
54 | In case you want to cancel a scheduled task on the fly you could pass the unique id of the task to WorkManager and call cancel
55 |
56 | ```swift
57 | WorkManager.shared.cancelQueuedPeriodicWork(withId: "com.unique.task.id")
58 | ```
59 |
60 | WorkManager As of now only performs the tasks in the foreground, it will evaluate every launch time if the time interval has passed against the last run time, which is a response to which it will perform your registered closure.
61 |
62 | ## Documentation
63 |
64 | [Refer here for the documentation](https://gojek.github.io/WorkManager/documentation/workmanager/)
65 |
66 | ## Contributing
67 |
68 | As the creators, and maintainers of this project, we're glad to invite contributors to help us stay up to date. Please take a moment to review [the contributing document](https://github.com/gojek/WorkManager/blob/main/.github/CONTRIBUTING.md) in order to make the contribution process easy and effective for everyone involved.
69 |
70 | - If you **found a bug**, open an [issue](https://github.com/gojek/WorkManager/issues).
71 | - If you **have a feature request**, open an [issue](https://github.com/gojek/WorkManager/issues).
72 | - If you **want to contribute**, submit a [pull request](https://github.com/gojek/WorkManager/pulls).
73 |
74 | ## License
75 |
76 | **WorkManager** is available under the MIT license. See the [LICENSE](https://github.com/gojek/WorkManager/blob/main/LICENSE) file for more info.
77 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to WorkManager
2 |
3 | As the creators, and maintainers of this project, we're glad to share our projects and invite contributors to help us stay up to date. Please take a moment to review this document in order to make the contribution process easy and effective for everyone involved.
4 |
5 | Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue or assessing patches and features.
6 |
7 | In general, we expect you to follow our [Code of Conduct](https://github.com/gojek/WorkManager/blob/main/CODE_OF_CONDUCT.md).
8 |
9 | ## Using Github Issues
10 |
11 | ### First time contributors
12 | We should encourage first time contributors. A good inspiration on this can be found [here](http://www.firsttimersonly.com/). As pointed out:
13 |
14 | > If you are an OSS project owner, then consider marking a few open issues with the label first-timers-only. The first-timers-only label explicitly announces:
15 |
16 | > "I'm willing to hold your hand so you can make your first PR. This issue is rather a bit easier than normal. And anyone who’s already contributed to open source isn’t allowed to touch this one!"
17 |
18 | By labeling issues with this `first-timers-only` label we help first time contributors step up their game and start contributing.
19 |
20 | ### Bug reports
21 |
22 | A bug is a _demonstrable problem_ that is caused by the code in the repository.
23 | Good bug reports are extremely helpful - thank you!
24 |
25 | Guidelines for bug reports:
26 |
27 | 1. **Use the GitHub issue search** — check if the issue has already been
28 | reported.
29 |
30 | 2. **Check if the issue has been fixed** — try to reproduce it using the
31 | latest `main` or `develop` branch in the repository.
32 |
33 | 3. **Isolate the problem** — provide clear steps to reproduce.
34 |
35 | A good bug report shouldn't leave others needing to chase you up for more information.
36 |
37 | Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What would you expect to be the outcome? All these details will help people to fix any potential bugs.
38 |
39 | Example:
40 |
41 | > Short and descriptive example bug report title
42 | >
43 | > A summary of the issue and the OS environment in which it occurs. If
44 | > suitable, include the steps required to reproduce the bug.
45 | >
46 | > 1. This is the first step
47 | > 2. This is the second step
48 | > 3. Further steps, etc.
49 | >
50 | > `` - a link to the reduced test case, if possible
51 | >
52 | > Any other information you want to share that is relevant to the issue being
53 | > reported. This might include the lines of code that you have identified as
54 | > causing the bug, and potential solutions (and your opinions on their
55 | > merits).
56 |
57 | ### Feature requests
58 |
59 | Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible.
60 |
61 | Do check if the feature request already exists. If it does, give it a thumbs-up emoji or even comment. We'd like to avoid duplicate requests.
62 |
63 | ### Pull requests
64 |
65 | Good pull requests - patches, improvements, new features - are a fantastic help. They should remain focused in scope and avoid containing unrelated commits.
66 |
67 | **Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code, porting to a different language), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project. As far as _where_ to ask, the feature request or bug report is the best place to go.
68 |
69 | Please adhere to the coding conventions used throughout a project (indentation, accurate comments, etc.) and any other requirements (such as test coverage).
70 |
71 | Follow this process if you'd like your work considered for inclusion in the project:
72 |
73 | 1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork, and configure the remotes:
74 |
75 | ```bash
76 | # Clone your fork of the repo into the current directory
77 | git clone git@github.com:YOUR_USERNAME/WorkManager.git
78 | # Navigate to the newly cloned directory
79 | cd WorkManager
80 | # Assign the original repo to a remote called "upstream"
81 | git remote add upstream git@github.com:gojek/WorkManager.git
82 | ```
83 |
84 | 2. If you cloned a while ago, get the latest changes from upstream:
85 |
86 | ```bash
87 | git checkout
88 | git pull upstream
89 | ```
90 |
91 | 3. Create a new topic branch (off the main project development branch) to
92 | contain your feature, change, or fix:
93 |
94 | ```bash
95 | git checkout -b
96 | ```
97 |
98 | 4. Commit your changes in logical chunks.
99 |
100 | 5. Locally merge (or rebase) the upstream development branch into your topic branch:
101 |
102 | ```bash
103 | git pull [--rebase] upstream
104 | ```
105 |
106 | 6. Push your topic branch up to your fork:
107 |
108 | ```bash
109 | git push origin
110 | ```
111 |
112 | 7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
113 | with a clear title and description.
114 |
115 | ### Conventions of commit messages
116 |
117 | Adding features on the repo
118 |
119 | ```bash
120 | git commit -m "feat: message about this feature"
121 | ```
122 |
123 | Fixing features on repo
124 |
125 | ```bash
126 | git commit -m "fix: message about this update"
127 | ```
128 |
129 | Removing features on repo
130 |
131 | ```bash
132 | git commit -m "refactor: message about this" -m "BREAKING CHANGE: message about the breaking change"
133 | ```
134 |
135 |
136 | **IMPORTANT**: By submitting a patch, you agree to allow the project owner to
137 | license your work under the same license as that used by the project, which is available [here](https://github.com/gojek/WorkManager/blob/main/LICENSE.md).
138 |
139 | ### Discussions
140 |
141 | We aim to keep all project discussions inside GitHub Issues. This is to make sure valuable discussion is accessible via search. If you have questions about how to use the library, or how the project is running - GitHub Issues are the go-to tool for this project.
142 |
143 | #### Our expectations of you as a contributor
144 |
145 | We want contributors to provide ideas, keep the ship shipping and to take some of the load from others. It is non-obligatory; we’re here to get things done in an enjoyable way. 🎉
146 |
147 | The fact that you'll have push access will allow you to:
148 |
149 | - Avoid having to fork the project if you want to submit other pull requests as you'll be able to create branches directly on the project.
150 | - Help triage issues, and merge pull requests.
151 | - Pick up the project if other maintainers move their focus elsewhere.
152 |
153 | Thanks! ❤️❤️❤️❤️❤️
154 |
155 | GO-JEK Tech
--------------------------------------------------------------------------------
/Sources/WorkManager/WorkManager.swift:
--------------------------------------------------------------------------------
1 | // Create by Amit Samant on 07/11/22
2 | //
3 | // WorkManager.swift
4 | // WorkManager
5 | //
6 | // Using Swift 5.0
7 | // Copyright © 2022 PT GoJek Indonesia. All rights reserved.
8 | // Licensed under Apache License v2.0
9 | //
10 |
11 | import Foundation
12 |
13 | /// Class responsible for scheduling periodic works
14 | public final class WorkManager {
15 |
16 | private init() {}
17 |
18 | /// Shared singleton object for WorkManager
19 | public static let shared: WorkManager = .init()
20 |
21 | private var taskMap: [String: Atomic] = [:]
22 | private let workManagerQueue = DispatchQueue(label: "workmanager.taskmap.concurrent", attributes: .concurrent)
23 |
24 | /// Enqueues periodic work, if task with same id exist the tasks are overridden
25 | /// - Parameters:
26 | /// - id: Unique id associated with work
27 | /// - interval: interval in seconds
28 | /// - work: Work block to perform periodically
29 | /// - doesNotPerformOnLowPower: defines if the work should run or low power mode
30 | /// - queue: Queue to run the task in, the default is background
31 | public func enqueueUniquePeriodicWork(id: String, interval: TimeInterval, work: @escaping () -> Void, doesNotPerformOnLowPower: Bool = true, onQueue queue: DispatchQueue = DispatchQueue.global(qos: .background)) {
32 | var task: Atomic?
33 | workManagerQueue.sync {
34 | task = self.taskMap[id]
35 | }
36 | if let existingTask = task {
37 | existingTask.mutate { task in
38 | task.op = work
39 | task.doesNotPerformOnLowPower = doesNotPerformOnLowPower
40 | task.scheduleTimeInterval = interval
41 | task.schedule()
42 | }
43 | } else {
44 | let newTask = Task(op: work, doesNotPerformOnLowPower: doesNotPerformOnLowPower, id: id, scheduleTimeInterval: interval, queue: queue)
45 | workManagerQueue.async(flags: .barrier) {
46 | self.taskMap[id] = Atomic(newTask)
47 | }
48 | newTask.schedule()
49 | }
50 | }
51 |
52 | /// Cancels scheduled task related to the unique id
53 | /// - Parameter id: Unique id of the task to be cancelled
54 | public func cancelQueuedPeriodicWork(withId id: String) {
55 | workManagerQueue.sync {
56 | taskMap[id]?.value.cancel()
57 | }
58 | workManagerQueue.async(flags: .barrier) {
59 | self.taskMap[id] = nil
60 | }
61 | }
62 | }
63 |
64 | // MARK: - Task Implementation
65 | extension WorkManager {
66 |
67 | /// Represents and periodic task, responsible for keeping track of execution timstamps
68 | public class Task {
69 | var op: () -> Void
70 | var doesNotPerformOnLowPower: Bool
71 | var id: String
72 | var scheduleTimeInterval: TimeInterval
73 | var queue: DispatchQueue
74 |
75 | private var currentWorkItem: DispatchWorkItem?
76 | private var lastRunTimeKey: String {
77 | id + "TimeKey"
78 | }
79 | private var lastRunTime: Date? {
80 | get {
81 | UserDefaults.standard.value(forKey: lastRunTimeKey) as? Date
82 | }
83 | set {
84 | UserDefaults.standard.set(newValue, forKey: lastRunTimeKey)
85 | }
86 | }
87 |
88 | public init(op: @escaping () -> Void, doesNotPerformOnLowPower: Bool, id: String, scheduleTimeInterval: TimeInterval, queue: DispatchQueue) {
89 | self.op = op
90 | self.doesNotPerformOnLowPower = doesNotPerformOnLowPower
91 | self.id = id
92 | self.scheduleTimeInterval = scheduleTimeInterval
93 | self.queue = queue
94 | NotificationCenter.default.addObserver(self, selector: #selector(schedule), name: Notification.Name.NSProcessInfoPowerStateDidChange, object: nil)
95 |
96 | }
97 |
98 | /// Perform/Execute the operration associated with the task object
99 | public func perform() {
100 | if doesNotPerformOnLowPower && ProcessInfo.processInfo.isLowPowerModeEnabled {
101 | return
102 | }
103 | op()
104 | }
105 |
106 | private func reschedule() {
107 | lastRunTime = Date()
108 | schedule()
109 | }
110 |
111 | private func performAndReschedule() {
112 | perform()
113 | reschedule()
114 | }
115 |
116 | private func scheduleTimer(timeIntervalSinceLastRun: TimeInterval? = nil) {
117 | // If the required time have not been elapsed the diffrence of time will be user to set a timer after which the startTracing will be called, this is for scenarios where the app has not been killed more than 24 hours, this timer will run every 24 hours and will push out the data
118 | let timeIntervalSinceLastRun = timeIntervalSinceLastRun ?? 0
119 | let diffTimeInterval = scheduleTimeInterval - timeIntervalSinceLastRun
120 | let workItem = DispatchWorkItem(block: self.performAndReschedule)
121 | queue.asyncAfter(
122 | deadline: .now() + diffTimeInterval,
123 | execute: workItem
124 | )
125 | currentWorkItem?.cancel()
126 | currentWorkItem = workItem
127 | }
128 |
129 | private func timeDependentScheduleOrRun(lastRunTime: Date) {
130 | let timeIntervalSinceLastRun = abs(lastRunTime.timeIntervalSinceNow)
131 | if timeIntervalSinceLastRun >= scheduleTimeInterval {
132 | performAndReschedule()
133 | } else {
134 | scheduleTimer(timeIntervalSinceLastRun: timeIntervalSinceLastRun)
135 | }
136 | }
137 |
138 | /// Cancel the ongoing task object
139 | public func cancel() {
140 | lastRunTime = nil
141 | currentWorkItem?.cancel()
142 | }
143 |
144 | /// Schedules the periodic task to run in provided intervals
145 | @objc public func schedule() {
146 | guard let lastRunTime = lastRunTime else {
147 | scheduleTimer()
148 | return
149 | }
150 | timeDependentScheduleOrRun(lastRunTime: lastRunTime)
151 | }
152 | }
153 | }
154 |
155 | // MARK: - Atomic implementation
156 | extension WorkManager {
157 |
158 | final class Atomic {
159 |
160 | private let dispatchQueue = DispatchQueue(label: "workmanager.atomic", attributes: .concurrent)
161 | private var _value: T
162 |
163 | init(_ value: T) {
164 | self._value = value
165 | }
166 |
167 | var value: T { dispatchQueue.sync { _value } }
168 |
169 | func mutate(execute task: (inout T) -> Void) {
170 | dispatchQueue.sync(flags: .barrier) { task(&_value) }
171 | }
172 |
173 | func mapValue(handler: ((T) -> U)) -> U {
174 | dispatchQueue.sync { handler(_value) }
175 | }
176 |
177 | }
178 | }
179 |
--------------------------------------------------------------------------------