Check if WorkManager is scheduled already












3















How can I check if WorkManager is scheduled already.



Here is my code that schedule WorkManager.



public static void scheduleWork() {
PeriodicWorkRequest.Builder photoCheckBuilder =
new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
TimeUnit.SECONDS);
PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
WorkManager instance = WorkManager.getInstance();
if (instance != null) {
instance.enqueueUniquePeriodicWork("TAG", ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
}
}


I call scheduleWork() in onCreate() of my Application class.
Even I can check my service is running or not by this method. But I don't want schedule WorkManager if it is already scheduled to remove inconsistency in scheduled time.



Like



if(!workManagerIsScheduled())
{
scheduleWork();
}


Any solutions?










share|improve this question























  • You can get status of work request...to check

    – Man
    Jul 31 '18 at 11:55











  • Did you try that?

    – Man
    Jul 31 '18 at 12:00











  • See answer @Man

    – Khemraj
    Jul 31 '18 at 12:11











  • there is no need to check if worker is already running since you are using instance.enqueueUniquePeriodicWork() with 'ExistingPeriodicWorkPolicy.KEEP'. It will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

    – Rai_Gaurav
    Jul 31 '18 at 12:11











  • 'ExistingPeriodicWorkPolicy.KEEP' is for a particular task, not for work. If some service is doing its work then this flag keep service running till it finish it's work.

    – Khemraj
    Jul 31 '18 at 12:13
















3















How can I check if WorkManager is scheduled already.



Here is my code that schedule WorkManager.



public static void scheduleWork() {
PeriodicWorkRequest.Builder photoCheckBuilder =
new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
TimeUnit.SECONDS);
PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
WorkManager instance = WorkManager.getInstance();
if (instance != null) {
instance.enqueueUniquePeriodicWork("TAG", ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
}
}


I call scheduleWork() in onCreate() of my Application class.
Even I can check my service is running or not by this method. But I don't want schedule WorkManager if it is already scheduled to remove inconsistency in scheduled time.



Like



if(!workManagerIsScheduled())
{
scheduleWork();
}


Any solutions?










share|improve this question























  • You can get status of work request...to check

    – Man
    Jul 31 '18 at 11:55











  • Did you try that?

    – Man
    Jul 31 '18 at 12:00











  • See answer @Man

    – Khemraj
    Jul 31 '18 at 12:11











  • there is no need to check if worker is already running since you are using instance.enqueueUniquePeriodicWork() with 'ExistingPeriodicWorkPolicy.KEEP'. It will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

    – Rai_Gaurav
    Jul 31 '18 at 12:11











  • 'ExistingPeriodicWorkPolicy.KEEP' is for a particular task, not for work. If some service is doing its work then this flag keep service running till it finish it's work.

    – Khemraj
    Jul 31 '18 at 12:13














3












3








3


2






How can I check if WorkManager is scheduled already.



Here is my code that schedule WorkManager.



public static void scheduleWork() {
PeriodicWorkRequest.Builder photoCheckBuilder =
new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
TimeUnit.SECONDS);
PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
WorkManager instance = WorkManager.getInstance();
if (instance != null) {
instance.enqueueUniquePeriodicWork("TAG", ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
}
}


I call scheduleWork() in onCreate() of my Application class.
Even I can check my service is running or not by this method. But I don't want schedule WorkManager if it is already scheduled to remove inconsistency in scheduled time.



Like



if(!workManagerIsScheduled())
{
scheduleWork();
}


Any solutions?










share|improve this question














How can I check if WorkManager is scheduled already.



Here is my code that schedule WorkManager.



public static void scheduleWork() {
PeriodicWorkRequest.Builder photoCheckBuilder =
new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
TimeUnit.SECONDS);
PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
WorkManager instance = WorkManager.getInstance();
if (instance != null) {
instance.enqueueUniquePeriodicWork("TAG", ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
}
}


I call scheduleWork() in onCreate() of my Application class.
Even I can check my service is running or not by this method. But I don't want schedule WorkManager if it is already scheduled to remove inconsistency in scheduled time.



Like



if(!workManagerIsScheduled())
{
scheduleWork();
}


Any solutions?







android android-workmanager






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 31 '18 at 11:25









KhemrajKhemraj

14.9k44788




14.9k44788













  • You can get status of work request...to check

    – Man
    Jul 31 '18 at 11:55











  • Did you try that?

    – Man
    Jul 31 '18 at 12:00











  • See answer @Man

    – Khemraj
    Jul 31 '18 at 12:11











  • there is no need to check if worker is already running since you are using instance.enqueueUniquePeriodicWork() with 'ExistingPeriodicWorkPolicy.KEEP'. It will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

    – Rai_Gaurav
    Jul 31 '18 at 12:11











  • 'ExistingPeriodicWorkPolicy.KEEP' is for a particular task, not for work. If some service is doing its work then this flag keep service running till it finish it's work.

    – Khemraj
    Jul 31 '18 at 12:13



















  • You can get status of work request...to check

    – Man
    Jul 31 '18 at 11:55











  • Did you try that?

    – Man
    Jul 31 '18 at 12:00











  • See answer @Man

    – Khemraj
    Jul 31 '18 at 12:11











  • there is no need to check if worker is already running since you are using instance.enqueueUniquePeriodicWork() with 'ExistingPeriodicWorkPolicy.KEEP'. It will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

    – Rai_Gaurav
    Jul 31 '18 at 12:11











  • 'ExistingPeriodicWorkPolicy.KEEP' is for a particular task, not for work. If some service is doing its work then this flag keep service running till it finish it's work.

    – Khemraj
    Jul 31 '18 at 12:13

















You can get status of work request...to check

– Man
Jul 31 '18 at 11:55





You can get status of work request...to check

– Man
Jul 31 '18 at 11:55













Did you try that?

– Man
Jul 31 '18 at 12:00





Did you try that?

– Man
Jul 31 '18 at 12:00













See answer @Man

– Khemraj
Jul 31 '18 at 12:11





See answer @Man

– Khemraj
Jul 31 '18 at 12:11













there is no need to check if worker is already running since you are using instance.enqueueUniquePeriodicWork() with 'ExistingPeriodicWorkPolicy.KEEP'. It will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

– Rai_Gaurav
Jul 31 '18 at 12:11





there is no need to check if worker is already running since you are using instance.enqueueUniquePeriodicWork() with 'ExistingPeriodicWorkPolicy.KEEP'. It will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

– Rai_Gaurav
Jul 31 '18 at 12:11













'ExistingPeriodicWorkPolicy.KEEP' is for a particular task, not for work. If some service is doing its work then this flag keep service running till it finish it's work.

– Khemraj
Jul 31 '18 at 12:13





'ExistingPeriodicWorkPolicy.KEEP' is for a particular task, not for work. If some service is doing its work then this flag keep service running till it finish it's work.

– Khemraj
Jul 31 '18 at 12:13












3 Answers
3






active

oldest

votes


















21














Update



If you need to check already running work manager just because you don't want duplicate works. You can simply use enqueueUniquePeriodicWork()




This method allows you to enqueue a uniquely-named
PeriodicWorkRequest, where only one PeriodicWorkRequest of a
particular name can be active at a time. For example, you may only
want one sync operation to be active. If there is one pending, you can
choose to let it run or replace it with your new work.




So you don't need to worry about duplicacy about works.



 workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);



  • Where TAG is unique name by which work manager will check duplicacy.

  • You can choose between ExistingPeriodicWorkPolicy.KEEP and ExistingPeriodicWorkPolicy.REPLACE.


Orignal Post



I created this method when I did not find any.



Check if work is running by TAG



if (your_work_manager.version >= 1.0.0-alpha11)



private boolean isWorkScheduled(String tag) {
WorkManager instance = WorkManager.getInstance();
ListenableFuture<List<WorkInfo>> statuses = instance.getWorkInfosByTag(tag);
try {
boolean running = false;
List<WorkInfo> workInfoList = statuses.get();
for (WorkInfo workInfo : workInfoList) {
WorkInfo.State state = workInfo.getState();
running = state == WorkInfo.State.RUNNING | state == WorkInfo.State.ENQUEUED;
}
return running;
} catch (ExecutionException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
}


if (your_work_manager.version < 1.0.0-alpha11)



private boolean isWorkScheduled(String tag) {
WorkManager instance = WorkManager.getInstance();
LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);
if (statuses.getValue() == null) return false;
boolean running = false;
for (WorkStatus workStatus : statuses.getValue()) {
running = workStatus.getState() == State.RUNNING | workStatus.getState() == State.ENQUEUED;
}
return running;
}


It will return true when some of its task is RUNNING or ENQUEUED.



Sample code



public static final String TAG_MY_WORK = "mywork";

if(!isWorkScheduled(TAG_MY_WORK)) { // check if your work is not already scheduled
scheduleWork(TAG_MY_WORK); // schedule your work
}

public static void scheduleWork(String tag) {
PeriodicWorkRequest.Builder photoCheckBuilder =
new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
TimeUnit.SECONDS);
PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
WorkManager instance = WorkManager.getInstance();
instance.enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
}





share|improve this answer


























  • Hello Khemraj your solution give me this type of error androidx.work.impl.utils.futures.SettableFuture cannot be cast to android.arch.lifecycle.LiveData It can not be cast LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);

    – Rahul Patil
    Nov 3 '18 at 7:12











  • If you wish to get livedata status then you have to change "getStatusesByTag(tag)" to "getStatusesByTagLiveData(tag)" as per new API.

    – Saurabh
    Nov 6 '18 at 6:14





















2














Problem with the answer which uses LiveData solution is that value can be null even if the job is scheduled and you should use Observer to check the status. To avoid this you can use SynchronousWorkManager.



public static boolean isWorkScheduled(String tag) {
SynchronousWorkManager instance = WorkManager.getInstance().synchronous();
List<WorkStatus> statuses = instance.getStatusesByTagSync(tag);
if (statuses.isEmpty()) return false;
boolean running = false;
for (WorkStatus workStatus : statuses) {
running = workStatus.getState() == State.RUNNING
| workStatus.getState() == State.ENQUEUED;
}
return running;
}


Of course the problem with this solution is that it cannot be run on a main Thread since it accesses the dabatase. But this solution is pretty good if you have multiple Workers but only one can run at the same time or if for some reason one Worker needs to schedule another one, which is my case.



EDIT:
Seems like SynchronousWorkManager was removed on October 11:




Removed WorkManager.synchronous() and WorkContinuation.synchronous() and all related methods. Added ListenableFuture as the return type of many methods in the API. This is a breaking API change.




How to use it:




You can now synchronously get and observe by using ListenableFutures. For example, WorkManager.enqueue() used to return void; it now returns a ListenableFuture. You can call ListenableFuture.addListener(Runnable, Executor) or ListenableFuture.get() to run code once the operation is complete.




More info can be found here.






share|improve this answer


























  • I can't seem to resolve SynchronousWorkManager in my project... has it been dropped?

    – drmrbrewer
    Dec 16 '18 at 17:46











  • Yes it seems to be gone since October 11. You can use ListenableFuture instead.

    – David Sucharda
    Dec 17 '18 at 14:48



















0














from 1.0.0-alpha11 along with many things WorkStatus will not work it's removed and it's a breaking change. Check Release Notes




WorkStatus has been renamed to WorkInfo. All corresponding getStatus method variants have been renamed to the corresponding getWorkInfo variants. This is a breaking change.




after updating to alpha11 the working code is.



private boolean isWorkScheduled(List<WorkInfo> workInfos) {

boolean running = false;

if (workInfos == null || workInfos.size() == 0) return false;

for (WorkInfo workStatus : workInfos) {
running = workStatus.getState() == WorkInfo.State.RUNNING | workStatus.getState() == WorkInfo.State.ENQUEUED;
}

return running;
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51612274%2fcheck-if-workmanager-is-scheduled-already%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    21














    Update



    If you need to check already running work manager just because you don't want duplicate works. You can simply use enqueueUniquePeriodicWork()




    This method allows you to enqueue a uniquely-named
    PeriodicWorkRequest, where only one PeriodicWorkRequest of a
    particular name can be active at a time. For example, you may only
    want one sync operation to be active. If there is one pending, you can
    choose to let it run or replace it with your new work.




    So you don't need to worry about duplicacy about works.



     workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);



    • Where TAG is unique name by which work manager will check duplicacy.

    • You can choose between ExistingPeriodicWorkPolicy.KEEP and ExistingPeriodicWorkPolicy.REPLACE.


    Orignal Post



    I created this method when I did not find any.



    Check if work is running by TAG



    if (your_work_manager.version >= 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    ListenableFuture<List<WorkInfo>> statuses = instance.getWorkInfosByTag(tag);
    try {
    boolean running = false;
    List<WorkInfo> workInfoList = statuses.get();
    for (WorkInfo workInfo : workInfoList) {
    WorkInfo.State state = workInfo.getState();
    running = state == WorkInfo.State.RUNNING | state == WorkInfo.State.ENQUEUED;
    }
    return running;
    } catch (ExecutionException e) {
    e.printStackTrace();
    return false;
    } catch (InterruptedException e) {
    e.printStackTrace();
    return false;
    }
    }


    if (your_work_manager.version < 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);
    if (statuses.getValue() == null) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses.getValue()) {
    running = workStatus.getState() == State.RUNNING | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    It will return true when some of its task is RUNNING or ENQUEUED.



    Sample code



    public static final String TAG_MY_WORK = "mywork";

    if(!isWorkScheduled(TAG_MY_WORK)) { // check if your work is not already scheduled
    scheduleWork(TAG_MY_WORK); // schedule your work
    }

    public static void scheduleWork(String tag) {
    PeriodicWorkRequest.Builder photoCheckBuilder =
    new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
    TimeUnit.SECONDS);
    PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
    WorkManager instance = WorkManager.getInstance();
    instance.enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
    }





    share|improve this answer


























    • Hello Khemraj your solution give me this type of error androidx.work.impl.utils.futures.SettableFuture cannot be cast to android.arch.lifecycle.LiveData It can not be cast LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);

      – Rahul Patil
      Nov 3 '18 at 7:12











    • If you wish to get livedata status then you have to change "getStatusesByTag(tag)" to "getStatusesByTagLiveData(tag)" as per new API.

      – Saurabh
      Nov 6 '18 at 6:14


















    21














    Update



    If you need to check already running work manager just because you don't want duplicate works. You can simply use enqueueUniquePeriodicWork()




    This method allows you to enqueue a uniquely-named
    PeriodicWorkRequest, where only one PeriodicWorkRequest of a
    particular name can be active at a time. For example, you may only
    want one sync operation to be active. If there is one pending, you can
    choose to let it run or replace it with your new work.




    So you don't need to worry about duplicacy about works.



     workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);



    • Where TAG is unique name by which work manager will check duplicacy.

    • You can choose between ExistingPeriodicWorkPolicy.KEEP and ExistingPeriodicWorkPolicy.REPLACE.


    Orignal Post



    I created this method when I did not find any.



    Check if work is running by TAG



    if (your_work_manager.version >= 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    ListenableFuture<List<WorkInfo>> statuses = instance.getWorkInfosByTag(tag);
    try {
    boolean running = false;
    List<WorkInfo> workInfoList = statuses.get();
    for (WorkInfo workInfo : workInfoList) {
    WorkInfo.State state = workInfo.getState();
    running = state == WorkInfo.State.RUNNING | state == WorkInfo.State.ENQUEUED;
    }
    return running;
    } catch (ExecutionException e) {
    e.printStackTrace();
    return false;
    } catch (InterruptedException e) {
    e.printStackTrace();
    return false;
    }
    }


    if (your_work_manager.version < 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);
    if (statuses.getValue() == null) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses.getValue()) {
    running = workStatus.getState() == State.RUNNING | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    It will return true when some of its task is RUNNING or ENQUEUED.



    Sample code



    public static final String TAG_MY_WORK = "mywork";

    if(!isWorkScheduled(TAG_MY_WORK)) { // check if your work is not already scheduled
    scheduleWork(TAG_MY_WORK); // schedule your work
    }

    public static void scheduleWork(String tag) {
    PeriodicWorkRequest.Builder photoCheckBuilder =
    new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
    TimeUnit.SECONDS);
    PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
    WorkManager instance = WorkManager.getInstance();
    instance.enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
    }





    share|improve this answer


























    • Hello Khemraj your solution give me this type of error androidx.work.impl.utils.futures.SettableFuture cannot be cast to android.arch.lifecycle.LiveData It can not be cast LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);

      – Rahul Patil
      Nov 3 '18 at 7:12











    • If you wish to get livedata status then you have to change "getStatusesByTag(tag)" to "getStatusesByTagLiveData(tag)" as per new API.

      – Saurabh
      Nov 6 '18 at 6:14
















    21












    21








    21







    Update



    If you need to check already running work manager just because you don't want duplicate works. You can simply use enqueueUniquePeriodicWork()




    This method allows you to enqueue a uniquely-named
    PeriodicWorkRequest, where only one PeriodicWorkRequest of a
    particular name can be active at a time. For example, you may only
    want one sync operation to be active. If there is one pending, you can
    choose to let it run or replace it with your new work.




    So you don't need to worry about duplicacy about works.



     workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);



    • Where TAG is unique name by which work manager will check duplicacy.

    • You can choose between ExistingPeriodicWorkPolicy.KEEP and ExistingPeriodicWorkPolicy.REPLACE.


    Orignal Post



    I created this method when I did not find any.



    Check if work is running by TAG



    if (your_work_manager.version >= 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    ListenableFuture<List<WorkInfo>> statuses = instance.getWorkInfosByTag(tag);
    try {
    boolean running = false;
    List<WorkInfo> workInfoList = statuses.get();
    for (WorkInfo workInfo : workInfoList) {
    WorkInfo.State state = workInfo.getState();
    running = state == WorkInfo.State.RUNNING | state == WorkInfo.State.ENQUEUED;
    }
    return running;
    } catch (ExecutionException e) {
    e.printStackTrace();
    return false;
    } catch (InterruptedException e) {
    e.printStackTrace();
    return false;
    }
    }


    if (your_work_manager.version < 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);
    if (statuses.getValue() == null) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses.getValue()) {
    running = workStatus.getState() == State.RUNNING | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    It will return true when some of its task is RUNNING or ENQUEUED.



    Sample code



    public static final String TAG_MY_WORK = "mywork";

    if(!isWorkScheduled(TAG_MY_WORK)) { // check if your work is not already scheduled
    scheduleWork(TAG_MY_WORK); // schedule your work
    }

    public static void scheduleWork(String tag) {
    PeriodicWorkRequest.Builder photoCheckBuilder =
    new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
    TimeUnit.SECONDS);
    PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
    WorkManager instance = WorkManager.getInstance();
    instance.enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
    }





    share|improve this answer















    Update



    If you need to check already running work manager just because you don't want duplicate works. You can simply use enqueueUniquePeriodicWork()




    This method allows you to enqueue a uniquely-named
    PeriodicWorkRequest, where only one PeriodicWorkRequest of a
    particular name can be active at a time. For example, you may only
    want one sync operation to be active. If there is one pending, you can
    choose to let it run or replace it with your new work.




    So you don't need to worry about duplicacy about works.



     workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);



    • Where TAG is unique name by which work manager will check duplicacy.

    • You can choose between ExistingPeriodicWorkPolicy.KEEP and ExistingPeriodicWorkPolicy.REPLACE.


    Orignal Post



    I created this method when I did not find any.



    Check if work is running by TAG



    if (your_work_manager.version >= 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    ListenableFuture<List<WorkInfo>> statuses = instance.getWorkInfosByTag(tag);
    try {
    boolean running = false;
    List<WorkInfo> workInfoList = statuses.get();
    for (WorkInfo workInfo : workInfoList) {
    WorkInfo.State state = workInfo.getState();
    running = state == WorkInfo.State.RUNNING | state == WorkInfo.State.ENQUEUED;
    }
    return running;
    } catch (ExecutionException e) {
    e.printStackTrace();
    return false;
    } catch (InterruptedException e) {
    e.printStackTrace();
    return false;
    }
    }


    if (your_work_manager.version < 1.0.0-alpha11)



    private boolean isWorkScheduled(String tag) {
    WorkManager instance = WorkManager.getInstance();
    LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);
    if (statuses.getValue() == null) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses.getValue()) {
    running = workStatus.getState() == State.RUNNING | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    It will return true when some of its task is RUNNING or ENQUEUED.



    Sample code



    public static final String TAG_MY_WORK = "mywork";

    if(!isWorkScheduled(TAG_MY_WORK)) { // check if your work is not already scheduled
    scheduleWork(TAG_MY_WORK); // schedule your work
    }

    public static void scheduleWork(String tag) {
    PeriodicWorkRequest.Builder photoCheckBuilder =
    new PeriodicWorkRequest.Builder(WorkManagerService.class, TIME_INTERVAL_IN_SECONDS,
    TimeUnit.SECONDS);
    PeriodicWorkRequest photoCheckWork = photoCheckBuilder.build();
    WorkManager instance = WorkManager.getInstance();
    instance.enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 21 '18 at 9:15

























    answered Jul 31 '18 at 12:11









    KhemrajKhemraj

    14.9k44788




    14.9k44788













    • Hello Khemraj your solution give me this type of error androidx.work.impl.utils.futures.SettableFuture cannot be cast to android.arch.lifecycle.LiveData It can not be cast LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);

      – Rahul Patil
      Nov 3 '18 at 7:12











    • If you wish to get livedata status then you have to change "getStatusesByTag(tag)" to "getStatusesByTagLiveData(tag)" as per new API.

      – Saurabh
      Nov 6 '18 at 6:14





















    • Hello Khemraj your solution give me this type of error androidx.work.impl.utils.futures.SettableFuture cannot be cast to android.arch.lifecycle.LiveData It can not be cast LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);

      – Rahul Patil
      Nov 3 '18 at 7:12











    • If you wish to get livedata status then you have to change "getStatusesByTag(tag)" to "getStatusesByTagLiveData(tag)" as per new API.

      – Saurabh
      Nov 6 '18 at 6:14



















    Hello Khemraj your solution give me this type of error androidx.work.impl.utils.futures.SettableFuture cannot be cast to android.arch.lifecycle.LiveData It can not be cast LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);

    – Rahul Patil
    Nov 3 '18 at 7:12





    Hello Khemraj your solution give me this type of error androidx.work.impl.utils.futures.SettableFuture cannot be cast to android.arch.lifecycle.LiveData It can not be cast LiveData<List<WorkStatus>> statuses = instance.getStatusesByTag(tag);

    – Rahul Patil
    Nov 3 '18 at 7:12













    If you wish to get livedata status then you have to change "getStatusesByTag(tag)" to "getStatusesByTagLiveData(tag)" as per new API.

    – Saurabh
    Nov 6 '18 at 6:14







    If you wish to get livedata status then you have to change "getStatusesByTag(tag)" to "getStatusesByTagLiveData(tag)" as per new API.

    – Saurabh
    Nov 6 '18 at 6:14















    2














    Problem with the answer which uses LiveData solution is that value can be null even if the job is scheduled and you should use Observer to check the status. To avoid this you can use SynchronousWorkManager.



    public static boolean isWorkScheduled(String tag) {
    SynchronousWorkManager instance = WorkManager.getInstance().synchronous();
    List<WorkStatus> statuses = instance.getStatusesByTagSync(tag);
    if (statuses.isEmpty()) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses) {
    running = workStatus.getState() == State.RUNNING
    | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    Of course the problem with this solution is that it cannot be run on a main Thread since it accesses the dabatase. But this solution is pretty good if you have multiple Workers but only one can run at the same time or if for some reason one Worker needs to schedule another one, which is my case.



    EDIT:
    Seems like SynchronousWorkManager was removed on October 11:




    Removed WorkManager.synchronous() and WorkContinuation.synchronous() and all related methods. Added ListenableFuture as the return type of many methods in the API. This is a breaking API change.




    How to use it:




    You can now synchronously get and observe by using ListenableFutures. For example, WorkManager.enqueue() used to return void; it now returns a ListenableFuture. You can call ListenableFuture.addListener(Runnable, Executor) or ListenableFuture.get() to run code once the operation is complete.




    More info can be found here.






    share|improve this answer


























    • I can't seem to resolve SynchronousWorkManager in my project... has it been dropped?

      – drmrbrewer
      Dec 16 '18 at 17:46











    • Yes it seems to be gone since October 11. You can use ListenableFuture instead.

      – David Sucharda
      Dec 17 '18 at 14:48
















    2














    Problem with the answer which uses LiveData solution is that value can be null even if the job is scheduled and you should use Observer to check the status. To avoid this you can use SynchronousWorkManager.



    public static boolean isWorkScheduled(String tag) {
    SynchronousWorkManager instance = WorkManager.getInstance().synchronous();
    List<WorkStatus> statuses = instance.getStatusesByTagSync(tag);
    if (statuses.isEmpty()) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses) {
    running = workStatus.getState() == State.RUNNING
    | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    Of course the problem with this solution is that it cannot be run on a main Thread since it accesses the dabatase. But this solution is pretty good if you have multiple Workers but only one can run at the same time or if for some reason one Worker needs to schedule another one, which is my case.



    EDIT:
    Seems like SynchronousWorkManager was removed on October 11:




    Removed WorkManager.synchronous() and WorkContinuation.synchronous() and all related methods. Added ListenableFuture as the return type of many methods in the API. This is a breaking API change.




    How to use it:




    You can now synchronously get and observe by using ListenableFutures. For example, WorkManager.enqueue() used to return void; it now returns a ListenableFuture. You can call ListenableFuture.addListener(Runnable, Executor) or ListenableFuture.get() to run code once the operation is complete.




    More info can be found here.






    share|improve this answer


























    • I can't seem to resolve SynchronousWorkManager in my project... has it been dropped?

      – drmrbrewer
      Dec 16 '18 at 17:46











    • Yes it seems to be gone since October 11. You can use ListenableFuture instead.

      – David Sucharda
      Dec 17 '18 at 14:48














    2












    2








    2







    Problem with the answer which uses LiveData solution is that value can be null even if the job is scheduled and you should use Observer to check the status. To avoid this you can use SynchronousWorkManager.



    public static boolean isWorkScheduled(String tag) {
    SynchronousWorkManager instance = WorkManager.getInstance().synchronous();
    List<WorkStatus> statuses = instance.getStatusesByTagSync(tag);
    if (statuses.isEmpty()) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses) {
    running = workStatus.getState() == State.RUNNING
    | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    Of course the problem with this solution is that it cannot be run on a main Thread since it accesses the dabatase. But this solution is pretty good if you have multiple Workers but only one can run at the same time or if for some reason one Worker needs to schedule another one, which is my case.



    EDIT:
    Seems like SynchronousWorkManager was removed on October 11:




    Removed WorkManager.synchronous() and WorkContinuation.synchronous() and all related methods. Added ListenableFuture as the return type of many methods in the API. This is a breaking API change.




    How to use it:




    You can now synchronously get and observe by using ListenableFutures. For example, WorkManager.enqueue() used to return void; it now returns a ListenableFuture. You can call ListenableFuture.addListener(Runnable, Executor) or ListenableFuture.get() to run code once the operation is complete.




    More info can be found here.






    share|improve this answer















    Problem with the answer which uses LiveData solution is that value can be null even if the job is scheduled and you should use Observer to check the status. To avoid this you can use SynchronousWorkManager.



    public static boolean isWorkScheduled(String tag) {
    SynchronousWorkManager instance = WorkManager.getInstance().synchronous();
    List<WorkStatus> statuses = instance.getStatusesByTagSync(tag);
    if (statuses.isEmpty()) return false;
    boolean running = false;
    for (WorkStatus workStatus : statuses) {
    running = workStatus.getState() == State.RUNNING
    | workStatus.getState() == State.ENQUEUED;
    }
    return running;
    }


    Of course the problem with this solution is that it cannot be run on a main Thread since it accesses the dabatase. But this solution is pretty good if you have multiple Workers but only one can run at the same time or if for some reason one Worker needs to schedule another one, which is my case.



    EDIT:
    Seems like SynchronousWorkManager was removed on October 11:




    Removed WorkManager.synchronous() and WorkContinuation.synchronous() and all related methods. Added ListenableFuture as the return type of many methods in the API. This is a breaking API change.




    How to use it:




    You can now synchronously get and observe by using ListenableFutures. For example, WorkManager.enqueue() used to return void; it now returns a ListenableFuture. You can call ListenableFuture.addListener(Runnable, Executor) or ListenableFuture.get() to run code once the operation is complete.




    More info can be found here.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 17 '18 at 14:45

























    answered Sep 22 '18 at 12:28









    David SuchardaDavid Sucharda

    30518




    30518













    • I can't seem to resolve SynchronousWorkManager in my project... has it been dropped?

      – drmrbrewer
      Dec 16 '18 at 17:46











    • Yes it seems to be gone since October 11. You can use ListenableFuture instead.

      – David Sucharda
      Dec 17 '18 at 14:48



















    • I can't seem to resolve SynchronousWorkManager in my project... has it been dropped?

      – drmrbrewer
      Dec 16 '18 at 17:46











    • Yes it seems to be gone since October 11. You can use ListenableFuture instead.

      – David Sucharda
      Dec 17 '18 at 14:48

















    I can't seem to resolve SynchronousWorkManager in my project... has it been dropped?

    – drmrbrewer
    Dec 16 '18 at 17:46





    I can't seem to resolve SynchronousWorkManager in my project... has it been dropped?

    – drmrbrewer
    Dec 16 '18 at 17:46













    Yes it seems to be gone since October 11. You can use ListenableFuture instead.

    – David Sucharda
    Dec 17 '18 at 14:48





    Yes it seems to be gone since October 11. You can use ListenableFuture instead.

    – David Sucharda
    Dec 17 '18 at 14:48











    0














    from 1.0.0-alpha11 along with many things WorkStatus will not work it's removed and it's a breaking change. Check Release Notes




    WorkStatus has been renamed to WorkInfo. All corresponding getStatus method variants have been renamed to the corresponding getWorkInfo variants. This is a breaking change.




    after updating to alpha11 the working code is.



    private boolean isWorkScheduled(List<WorkInfo> workInfos) {

    boolean running = false;

    if (workInfos == null || workInfos.size() == 0) return false;

    for (WorkInfo workStatus : workInfos) {
    running = workStatus.getState() == WorkInfo.State.RUNNING | workStatus.getState() == WorkInfo.State.ENQUEUED;
    }

    return running;
    }





    share|improve this answer




























      0














      from 1.0.0-alpha11 along with many things WorkStatus will not work it's removed and it's a breaking change. Check Release Notes




      WorkStatus has been renamed to WorkInfo. All corresponding getStatus method variants have been renamed to the corresponding getWorkInfo variants. This is a breaking change.




      after updating to alpha11 the working code is.



      private boolean isWorkScheduled(List<WorkInfo> workInfos) {

      boolean running = false;

      if (workInfos == null || workInfos.size() == 0) return false;

      for (WorkInfo workStatus : workInfos) {
      running = workStatus.getState() == WorkInfo.State.RUNNING | workStatus.getState() == WorkInfo.State.ENQUEUED;
      }

      return running;
      }





      share|improve this answer


























        0












        0








        0







        from 1.0.0-alpha11 along with many things WorkStatus will not work it's removed and it's a breaking change. Check Release Notes




        WorkStatus has been renamed to WorkInfo. All corresponding getStatus method variants have been renamed to the corresponding getWorkInfo variants. This is a breaking change.




        after updating to alpha11 the working code is.



        private boolean isWorkScheduled(List<WorkInfo> workInfos) {

        boolean running = false;

        if (workInfos == null || workInfos.size() == 0) return false;

        for (WorkInfo workStatus : workInfos) {
        running = workStatus.getState() == WorkInfo.State.RUNNING | workStatus.getState() == WorkInfo.State.ENQUEUED;
        }

        return running;
        }





        share|improve this answer













        from 1.0.0-alpha11 along with many things WorkStatus will not work it's removed and it's a breaking change. Check Release Notes




        WorkStatus has been renamed to WorkInfo. All corresponding getStatus method variants have been renamed to the corresponding getWorkInfo variants. This is a breaking change.




        after updating to alpha11 the working code is.



        private boolean isWorkScheduled(List<WorkInfo> workInfos) {

        boolean running = false;

        if (workInfos == null || workInfos.size() == 0) return false;

        for (WorkInfo workStatus : workInfos) {
        running = workStatus.getState() == WorkInfo.State.RUNNING | workStatus.getState() == WorkInfo.State.ENQUEUED;
        }

        return running;
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 '18 at 12:11









        IrfanIrfan

        676512




        676512






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51612274%2fcheck-if-workmanager-is-scheduled-already%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings