Hi I need to set time to live programmatically for a table in DynamoDB via AWS Java SDK. Is it possible? I know that TTL feature is introduced recently - http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html
UPDATE:
There is no special annotaion, but we can do it manually:
#DynamoDBAttribute
private long ttl;
and configure it as ttl in AWS - http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html
long now = Instant.now().getEpochSecond(); // unix time
long ttl = 60 * 60 * 24; // 24 hours in sec
setTtl(ttl + now); // when object will be expired
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html
public void function(final AmazonDynamoDB client, final String tableName, final String ttlField){
//table created now enabling TTL
final UpdateTimeToLiveRequest req = new UpdateTimeToLiveRequest();
req.setTableName(tableName);
final TimeToLiveSpecification ttlSpec = new TimeToLiveSpecification();
ttlSpec.setAttributeName(ttlField);
ttlSpec.setEnabled(true);
req.withTimeToLiveSpecification(ttlSpec);
client.updateTimeToLive(req);
}
AmazonDynamoDBClient.updateTimeToLive documented here or direct link here
Code Sample here.
//Then set ttl field like below for days in java
//ttl 60 days
Calendar cal = Calendar.getInstance(); //current date and time
cal.add(Calendar.DAY_OF_MONTH, 60); //add days
double ttl = (cal.getTimeInMillis() / 1000L);
Related
I' trying to get the screen interactive time from Androids "usageStatsManagers" "queryEventStats" Method.
With the code i wrote, I'm able to get a list that looks like this:
EventStats: [android.app.usage.EventStats#2ada570, android.app.usage.EventStats#f7c0e9,
Code:
UsageStatsManager usm = (UsageStatsManager) getContext().getSystemService(Context.USAGE_STATS_SERVICE);
long now = Calendar.getInstance().getTimeInMillis();
Calendar beginCal = Calendar.getInstance();
beginCal.set(Calendar.DATE, 1);
beginCal.set(Calendar.MONTH, 10);
beginCal.set(Calendar.YEAR, 2022);
Calendar endCal = Calendar.getInstance();
endCal.set(Calendar.DATE, 8);
endCal.set(Calendar.MONTH, 11);
endCal.set(Calendar.YEAR, 2022);
List<EventStats> stats = usm.queryEventStats(
UsageStatsManager.INTERVAL_DAILY,
beginCal.getTimeInMillis(),
endCal.getTimeInMillis()
);
System.out.println("EventStats: " + stats);
The Android documentation says:
The current event types that will be aggregated here are:
UsageEvents.Event#SCREEN_INTERACTIVE...
My question is: How to get this SCREEN_INTERACTIVE time from this List I got in "stats" ? And also some more details about these stats other than that cryptic name I got in the List?
I am trying to query ListOpenWorkflowExecutions using WorkflowServiceTChannel. I always get ListOpenWorkflowExecutionsResponse size of 0. I am unable to figure out where I am going wrong. Following is the java code i am using.
IWorkflowService cadenceService = new WorkflowServiceTChannel(ipAddress, 7933);
// Start Window
Calendar startCal = Calendar.getInstance();
startCal.add(Calendar.HOUR_OF_DAY, -24);
// End Window
Calendar endCal = Calendar.getInstance();
StartTimeFilter timeFilter = new StartTimeFilter();
timeFilter.setEarliestTime(startCal.getTimeInMillis());
timeFilter.setLatestTime(endCal.getTimeInMillis());
ListOpenWorkflowExecutionsRequest request = new ListOpenWorkflowExecutionsRequest();
request.setStartTimeFilter(timeFilter);
request.setDomain("staging");
ListOpenWorkflowExecutionsResponse response =
cadenceService.ListOpenWorkflowExecutions(request);
System.out.println(response.getExecutionsSize());
I have figured out a way. Timestamp shall be in nanos instead of mills. Following code worked for me.
Thanks to Maxim who helped me on Cadence slack channel.
StartTimeFilter timeFilter = new StartTimeFilter();
timeFilter.setEarliestTime(TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis() - 100000));
timeFilter.setLatestTime(TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis() + 100000));
ListOpenWorkflowExecutionsRequest request = new ListOpenWorkflowExecutionsRequest();
request.setStartTimeFilter(timeFilter);
request.setDomain(domain);
ListOpenWorkflowExecutionsResponse response = cadenceService.ListOpenWorkflowExecutions(request);
int openWorkflows = response.getExecutionsSize();
LOG.info("open workflows - {}, domain - {}", openWorkflows, domain);
I have an android service that runs on background, sample sensors and write them to a file with their time-stamp.
I have also a java application that read from this file, and want to compare the time now with the time-stamp from the file.
My android device time set to my PC time, but:
The time-stamp (on milli seconds) are different from my java time.
Any one have an idea how to compare the different times?
Java:
System.currentTimeMillis()
1460272414374
Android:
/**
* The time in nanosecond at which the event happened
*/
public long timestamp;
event.timestamp: 190174864000
Thanks
long timeInMillis = (new Date()).getTime()
+ (sensorEvent.timestamp - System.nanoTime()) / 1000000L;
SystemClock.elapsedRealtimeNanos() is the API . sensorTimeStamp in device's local time reference = System.currentTimeMillis() + ((event.timestamp-SystemClock.elapsedRealtimeNanos())/1000000L)
private long sensorTimeReference = 0l;
private long myTimeReference = 0l;
public void onSensorChanged(SensorEvent event) {
// set reference times
if(sensorTimeReference == 0l && myTimeReference == 0l) {
sensorTimeReference = event.timestamp;
myTimeReference = System.currentTimeMillis();
}
// set event timestamp to current time in milliseconds
event.timestamp = myTimeReference +
Math.round((event.timestamp - sensorTimeReference) / 1000000.0);
// some code...
}
I want to fetch the Cloudmetrics data for my EC2 instance so that I can draw graphs using those data and display it on my android device. How do I do that? Is there any sample program or tutorial for the same?
Thanks in advance.
This is what I am doing:
private static void findCloudWatchData() {
AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(new BasicAWSCredentials(AccessKey, SecretKey));
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("instanceid");
instanceDimension.setValue(instanceid);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
.withStartTime(new Date(new Date().getTime() - offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withMetricName("CPUUtilization")
.withStatistics("Average")
.withDimensions(Arrays.asList(instanceDimension))
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch.getMetricStatistics(request);
}
As you have tagged your question with android I assume that you want to fetch CloudWatch-Metrics for your EC2 Instances in an Android-App.
So this might be a good starting point for you:
Getting Started with the AWS SDK for Android .
You need to:
download AWS SDK for Android
create your access keys for AWS (via IAM)
read the documentation for aws-android-sdk-VERSION-cloudwatch.jar
start using the fetched data from CloudWatch
Regards
Tom
I suppose you are struck only with reading the data and plotting the graph.
private static void findCloudWatchData() {
LinkedHashMap<Date,Double> map=new HashMap<Date,Double>();
AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(new BasicAWSCredentials(AccessKey, SecretKey));
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("instanceid");
instanceDimension.setValue(instanceid);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
.withStartTime(new Date(new Date().getTime() - offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withMetricName("CPUUtilization")
.withStatistics("Average")
.withDimensions(Arrays.asList(instanceDimension))
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch.getMetricStatistics(request);
}
//To read the Data
for (Datapoint dp : result.getDatapoints()) {
map.put(dp.getTimeStamp(), dp.getAverage()); //or getMaximum() or whatever Statistics you are interested in. You can also maintain a list of the statistics you are interested in. Ex: request.setStatistics(list)
}
Note that the datapoints are NOT in order. Sort the HashMap and plot the graph.
I found that AWS/Billing metrics "live" only in one region - us-east-1.
Also, AWS CLI (aws cloudwatch get-metric-statistics) will errorr out if you try to grab more than 1440 data points from CloudWatch.
If you encounter it set larger --period.
Similar to what you are trying to achieve using Java on Android I wrote EC2_Metrics_Plotter for OS Windows using Python/matplotlib.
I have 2 events in my application. I need the time difference between the two of them so I store the time in a sharedpreferences using this line of code :
public static void PutStatus(Context ctx,boolean stat)
{
if (ctx != null)
{
SharedPreferences shr = ctx.getSharedPreferences("test", Context.MODE_WORLD_READABLE);
shr.edit().putBoolean("SHIFT", stat).commit();
if (stat) shr.edit().putLong("START_TIME", System.currentTimeMillis()).commit();
}
}
And then I calculate the difference between the two date and times using this :
SharedPreferences shr = getApplicationContext().getSharedPreferences("test", Context.MODE_WORLD_READABLE);
long time_stamp = System.currentTimeMillis() - shr.getLong("START_TIME", 0);
Date data = new Date(time_stamp);
The minutes are working great but the hours are 2 hour ahead.
Why is that does it have any connection with timezones ?
The proper way to get a duration with Java is a little bit complicated. You would create it the following way:
import javax.xml.datatype.Duration;
import javax.xml.datatype.DatatypeFactory
...
Duration d = DatatypeFactory.newInstance().newDuration(time_stamp);
System.out.println(d.getHours() + "h:" + d.getMinutes() + "m: " + d.getSeconds() + "s");
For documentation see Duration and DatatypeFactory.
If you need time interval, what about just doing some modulo computations? An hour is 3600 * 1000 milliseconds, day is 86400 * 1000. When you create date this way, you are creating date object relative to 1.1.1970 UTC - this may be as well 2 hours off from timezone where your phone thinks to be.
I would suggest to use two date objects, something like
int diffInDays = (newerDate.getTime() - olderDate.getTime()) / (1000 * 60 * 60 * 24)