Keep alive a background thread using PARTIAL_WAKE_LOCK
<p>I need to periodically run a task in background, and to keep awake the CPU. According to the Android <a href="https://developer.android.com/reference/android/os/PowerManager.html" rel="nofollow noreferrer">documentation</a> i used the <strong>PARTIAL_WAKE_LOCK</strong> for this purpose.
In order to test the wake lock, i wrote a Service which starts a thread every 2 minutes using a <strong>ScheduledThreadPoolExecutor</strong>. This thread just write a string on a log file in the sdcard.</p>

<p>Then, i performed the following simple test: run the application and unplug the device from the power. After 2 or 3 hours of correct execution, the Service stops to run the thread and no new strings are written in the log file.</p>

<p>Service's code:</p>

<pre><code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.d(TAG, "Service onStartCommand");

    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WiOpp wakeLock");
    wakeLock.acquire();

    TestTask testTask = new TestTask(getApplicationContext());
    ScheduledThreadPoolExecutor monitorPool = new ScheduledThreadPoolExecutor(1);
    monitorPool.scheduleAtFixedRate(testTask, 0, 120, TimeUnit.SECONDS);

    return START_STICKY;
}
</code></pre>

<p>TestTask's code:</p>

<pre><code>@Override
public void run() {
    //write on log file
    LogManager.getInstance().logData("I am running!");
}
</code></pre>

<p>I expect that the thread is also executed when the display is turned off, but looking my log file it seems not to be so. Where am I wrong?</p>