background-task.cpp 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * background-task.cpp
 * Copyright (C) 2010-2018 Belledonne Communications SARL
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "background-task.h"
#include "c-wrapper/internal/c-sal.h"
#include "logger/logger.h"
23
#include "core/core-p.h"
24 25 26

// TODO: Remove me
#include "private.h" // To get access to the Sal
27 28 29 30 31

// =============================================================================

LINPHONE_BEGIN_NAMESPACE

32
void BackgroundTask::sHandleTimeout (void *context) {
33 34 35
	static_cast<BackgroundTask *>(context)->handleTimeout();
}

36
int BackgroundTask::sHandleSalTimeout (void *data, unsigned int events) {
37 38 39 40
	static_cast<BackgroundTask *>(data)->handleSalTimeout();
	return BELLE_SIP_STOP;
}

41 42
void BackgroundTask::handleSalTimeout () {
	lWarning() << "Background task [" << mId << "] with name: [" << mName << "] is now expiring";
43 44 45
	stop();
}

46
void BackgroundTask::start (const std::shared_ptr<Core> &core, int maxDurationSeconds) {
47
	if (mName.empty()) {
48
		lError() << "No name was set on background task";
49 50 51
		return;
	}

52
	unsigned long newId = sal_begin_background_task(mName.c_str(), sHandleTimeout, this);
53
	stop();
54 55 56 57 58
	if (newId == 0)
		return;

	lInfo() << "Starting background task [" << newId << "] with name: [" << mName
		<< "] and expiration of [" << maxDurationSeconds << "]";
59
	mId = newId;
60
	if (maxDurationSeconds > 0) {
61
		mSal = core->getCCore()->sal;
62
		mTimeout = mSal->create_timer(sHandleSalTimeout, this, (unsigned int)maxDurationSeconds * 1000, mName.c_str());
63
	}
64 65 66 67 68 69
}

void BackgroundTask::stop () {
	if (mId == 0)
		return;

70
	lInfo() << "Ending background task [" << mId << "] with name: [" << mName << "]";
71
	sal_end_background_task(mId);
72
	if (mTimeout) {
73 74
		mSal->cancel_timer(mTimeout);
		belle_sip_object_unref(mTimeout);
75
		mTimeout = nullptr;
76
	}
77 78 79
	mId = 0;
}

80
void BackgroundTask::handleTimeout () {
81 82
	lWarning() << "Background task [" << mId << "] with name: [" << mName
		<< "] is expiring from OS before completion...";
83 84 85
	stop();
}

86
LINPHONE_END_NAMESPACE