User guide

// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstances
Request();
20 // Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Set the type of the bid to persistent.
25 requestRequest.setType("persistent");
// Set up the specifications of the launch. This includes the
// instance type (e.g. t1.micro) and the latest Amazon Linux
// AMI id available. Note, you should always use the latest
30 // Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
35 // Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
40 // Add the launch specification.
requestRequest.setLaunchSpecification(launchSpecification);
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(re
questRequest);
45
Limiting the Duration of a Request
You can also optionally specify the length of time that your request will remain valid.You can specify both
a starting and ending time for this period. By default, a Spot request will be considered for fulfillment from
the moment it is created until it is either fulfilled or canceled by you. However you can constrain the validity
period if you need to. An example of how to specify this period is shown in the following code.
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = new AmazonEC2Client(credentials);
15
Version v1.0.0
49
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management