Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
huangzhicong
/
SmartCanteen
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
29fa5e2b
authored
Aug 03, 2019
by
patpat
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
增加TimerHelper
parent
9b326807
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
75 additions
and
0 deletions
+75
-0
app/src/main/java/com/bgycc/smartcanteen/helper/TimerHelper.kt
+75
-0
No files found.
app/src/main/java/com/bgycc/smartcanteen/helper/TimerHelper.kt
0 → 100644
View file @
29fa5e2b
package
com.bgycc.smartcanteen.helper
import
android.util.Log
import
android.util.LongSparseArray
import
java.lang.Exception
import
java.util.concurrent.Executors
import
java.util.concurrent.ScheduledFuture
import
java.util.concurrent.TimeUnit
object
TimerHelper
{
val
TAG
=
TimerHelper
::
class
.
java
.
simpleName
private
var
mId
:
Long
=
0L
get
()
=
++
field
private
val
mScheduledExecutorService
=
Executors
.
newScheduledThreadPool
(
3
)
private
val
mFutureList
=
LongSparseArray
<
ScheduledFuture
<*>>()
fun
shutdown
()
{
mFutureList
.
clear
()
mScheduledExecutorService
.
shutdown
()
}
@Synchronized
fun
cancel
(
id
:
Long
)
{
try
{
val
future
=
mFutureList
.
get
(
id
)
?:
return
mFutureList
.
remove
(
id
)
future
.
cancel
(
true
)
}
catch
(
e
:
Exception
)
{}
}
fun
timeout
(
runnable
:
()
->
Unit
,
time
:
Long
):
Long
{
val
id
=
mId
mFutureList
.
put
(
id
,
mScheduledExecutorService
.
schedule
({
mFutureList
.
remove
(
id
)
runnable
()
},
time
,
TimeUnit
.
MILLISECONDS
))
return
id
}
fun
loop
(
runnable
:
(
id
:
Long
)
->
Boolean
,
period
:
Long
,
times
:
Int
=
-
1
):
Long
{
val
id
=
mId
mFutureList
.
put
(
id
,
mScheduledExecutorService
.
scheduleWithFixedDelay
(
object
:
Runnable
{
var
vTimes
=
0
override
fun
run
()
{
if
(
times
>=
0
)
{
vTimes
++
if
(
vTimes
>
times
)
{
cancel
(
id
)
return
}
}
if
(!
runnable
(
id
))
{
cancel
(
id
)
}
}
},
0
,
period
,
TimeUnit
.
MILLISECONDS
))
return
id
}
fun
test
()
{
Log
.
i
(
TAG
,
"start"
)
timeout
({
Log
.
i
(
TAG
,
"timeout"
)
},
1000
)
loop
({
Log
.
i
(
TAG
,
"loop"
)
return
@loop
true
},
1000
,
4
)
}
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment